So I'm using Spree as my shopping cart in Ruby on Rails. Spree is version 1-1-stable, and Ruby is v1.9.3, and Ruby on Rails is v3.2.3.
I have a remote host that has images that I want to download for my Spree cart. This is the code I'm using to pull it. Some of it may not make sense, because I'm trying to do whatever I can to get this to work so it could use a little cleaning.
# Add image to the product
vendor_id = plink_and_pull(item, "VendorID")
image_name = plink_and_pull(item, "ImageName")
# TODO: add if image exists to this unless
unless image_name.nil? || vendor_id.nil? || plink_and_pull(item, "ImageFound").to_i == 0 || File.exists?("/public/prod_images/#{vendor_id}/#{image_name.gsub(' ', '%20')}")
unless Dir.exists? "/public/prod_images/#{vendor_id}"
Dir.mkdir("/public/prod_images/#{vendor_id}", 777)
end
file = File.new("public/prod_images/#{vendor_id}/#{image_name.gsub(' ', '%20')}", 'w+')
file.binmode
open(URI.parse("http://login.xolights.com/vendors/#{vendor_id}/large/#{image_name.gsub(' ', '%20')}")) do |data|
file.write data.read
end
img = Spree::Image.create({:attachment => "public/prod_images/#{vendor_id}/#{image_name}",
:viewable => product}, :without_protection => true)
end
But the error I get says "No such file or directory - /public/prod_images/29" and it references the "Dir.mkdir" line up there. However, I manually created this directory to try to get it to work. In my exception rescue I have the working directory printed out, which is the base directory of my app on my machine. (I am running this on localhost atm.)
I am thinking that maybe I need to do something in my routes.rb file? But I am such a novice at Ruby on Rails routes that I'm not sure where to start... or even if that's the problem here.
I am not that familiar with RubyMine. But rest assured that it's not about routes. It's not Rails-specific. It's Ruby (and OS)-specific because Dir.mkdir is part of standard Ruby library. Just remove the leading / from the path and see whether it works. (So, the actual path will be {your Rails app's root directory}/public/prod_images
Related
background
I am trying to migrate an old Rails 2 (Ruby 1.8.7) app to Rails 3.0.9 (Ruby 1.9.3) — yes it's a stepping stone to get it to Rails 4 and Ruby 2.2 — and I've hit the following problem.
The original app makes extensive use of an old Active Form gem which we've hacked slightly to support Ruby 1.9.
It mostly works, but there appears to be some issue with how it interacts with the ActionView::Helpers::AssetTagHelper that's part of ActionPack 3.0.9.
In my specific case I have an ActiveForm::DateCalendarSection (built dynamically) which subclasses ActiveForm::Element::Section, which, according to self.class.ancestors, is a subclass of ActionView::Helpers::AssetTagHelper. Looking at the ActiveForm source however there is no mention of AssetTagHelper or asset_tag_helper so how they are actually connected remains a mystery to me.
Problem
Calls to the method image_path result in an error
undefined local variable or method 'config'
The call to image_path is simply a wrapper around a call to compute_public_path in ActionView::Helpers::AssetTagHelper
# File actionpack/lib/action_view/helpers/asset_tag_helper.rb, line 741
def compute_public_path(source, dir, ext = nil, include_host = true)
return source if is_uri?(source)
source += ".#{ext}" if rewrite_extension?(source, dir, ext)
source = "/#{dir}/#{source}" unless source[0] == //
source = rewrite_asset_path(source, config.asset_path)
has_request = controller.respond_to?(:request)
if has_request && include_host && source !~ %{^#{controller.config.relative_url_root}/}
source = "#{controller.config.relative_url_root}#{source}"
end
source = rewrite_host_and_protocol(source, has_request) if include_host
source
end
Diving into that with binding.pry it's evident that config is indeed not defined. Likewise controller is also not defined.
Question
What would have changed between Rails 2 and Rails 3, such that methods from ActionView::Helpers::AssetTagHelper can no longer access Rails' config or the current controller?
It could be you don't have enough of the Rails support loaded. Maybe pull in everything inside your gem with
require "active_support/all"
Alternatively, have a look at how modern Rails hooks things up via a proxy to the config:
https://github.com/rails/rails/pull/12622/files
We have a use case where we need to run assets:precompile outside of the deploy/restart process, and therefore preferably without having to restart the Rails server processes. Is this possible in a Passenger environment?
I've been banging my head trying a bunch of stuff within Rake tasks and fiddling with Rails.application.config.assets stuff, but nothing makes the application pickup the changes to the digests except restarting Passenger with /usr/bin/env touch ~/project/current/tmp/restart.txt
We ended up going with a 2 part solution:
Part 1 is to setup the app to hit redis to store an 'assets:version' (we just went with a timestamp). Then, whenever our process was done precompiling, we update this assets version with the latest timestamp.
Part 2 was that we added a before_filter :check_assets_version in our main application_controller that all our other controllers inherit from. This method looks something like this:
def check_assets_version
##version ||= 1
latest_version = get_assets_version # wrapped call to redis to get latest version
# clear assets cache if current version isn't the same as the latest version from redis
unless latest_version.blank? || latest_version.to_s == ##version
##version = latest_version
if Rails.env.production? || Rails.env.sandbox? || Rails.env.experimental?
nondev_reset_sprockets
else
dev_reset_sprockets ##version
end
end
end
And those two reset methods look like this:
def nondev_reset_sprockets
manifest = YAML.load(File.read(Rails.root.join("public","assets","manifest.yml")))
manifest.each do |key, value|
Rails.application.config.assets.digests[key] = value
end
end
The nondev reset "stuffs" each of the values into memory from the new generated manifest file
def dev_reset_sprockets(version)
environment = Rails.application.assets
environment = environment.instance_variable_get('#environment') if environment.is_a?(Sprockets::Index)
environment.version = version
end
The dev reset just kicks sprockets "version" value so that it thinks (correctly so) it needs to reparse and live recompile the latest assets.
Another way of updating the assets in production is as follows:
Rails.application.assets_manifest.instance_eval do
new_manifest = Sprockets::Manifest.new(manifest.dir, manifest.filename)
#data = new_manifest.instance_variable_get(:#data)
end
For Rails 4 (Sprockets 2.11), you can do:
Rails.application.assets_manifest = Sprockets::Manifest.new(Rails.env, Rails.application.assets_manifest.path)
# see sprockets-rails/lib/railtie.rb
ActionView::Base.assets_manifest = Rails.application.assets_manifest
Using deploy.rb to precompile rails assets only when they change, this task is always skipping the compile of my assets :(
namespace :assets do
task :precompile, :roles => :web, :except => {:no_release => true} do
from = source.next_revision(current_revision)
if capture("cd #{latest_release} && #{source.local.log(from)} vendor/assets/ app/assets/ | wc -l").to_i > 0
run %Q{cd #{latest_release} && #{rake} RAILS_ENV=#{rails_env} #{asset_env} assets:precompile}
else
logger.info "Skipping asset pre-compilation because there were no asset changes"
end
end
end
What could causing this complete task not compiling? It always thinks there are no asset changes and throws that message.
I also never really understood the task, for example what does below source.log.local refer to?
source.local.log
Could anyone clarify what the task commands do and has some pointers why it never sees any asset changes? Thank you
What it does:
from = source.next_revision(current_revision)
source is a reference to your source code, as seen through your SCM (git, svn, whatever). This sets from as (essentially) the currently deployed version of your source code.
capture("cd #{latest_release} && #{source.local.log(from)} vendor/assets/ app/assets/ | wc -l")
capture means 'execute this command in the shell, and return its output'. The command in question references the log of changes to your source comparing the deployed version to the current version (specifying the paths where assets live as the ones that 'matter'), and passes that into the word count tool (wc -l). The -l option means that it returns a count of the number of lines in the output. Thus, the output (which is returned by capture) is the number of filenames that have changes between these two versions.
If that number is zero, then no files have changed in any of the specified paths, so we skip precompiling.
Why it doesn't work:
I don't know. There doesn't seem to be anything wrong with the code itself - it's the same snippet I use, more or less. Here's a couple of things that you can check:
Does Capistrano even know you're using the asset pipeline? Check your Capfile. If you don't have load 'deploy/assets' in there, deploying won't even consider compiling your assets.
Have you, in fact, enabled the asset pipeline? Check application.rb for config.assets.enabled = true
Do you have incorrect asset paths specified? The code is checking for changes in vendor/assets/ and app/assets/. If your assets live somewhere else (lib/assets, for instance), they won't be noticed. (If this is the case, you can just change that line to include the correct paths.
Have you, in fact, changed any assets since the last deployment? I recommend bypassing the check for changed assets and forcing precompile to run once, then turning the check back on and seeing it the problem magically resolves itself. In my example, below, setting force_precompile = true would do that.
What I use:
Here's the version of this I currently use. It may be helpful. Or not. Changes from the original:
A more readable way to specify asset paths (if you use it, remember to set asset_locations to the places your assets live)
An easy way to force precompile to run (set force_precompile=true to attempt to run the check, but run precompile regardless)
It prints out the count whether or not precompile runs. I appreciate getting some output just to be sure the check is running.
If an error occurs when trying to compare the files (as will often happen with brand new projects, for instance), it prints the error but runs precompile anyway.
.
namespace :assets do
task :precompile, :roles => :web, :except => { :no_release => true } do
# Check if assets have changed. If not, don't run the precompile task - it takes a long time.
force_compile = false
changed_asset_count = 0
begin
from = source.next_revision(current_revision)
asset_locations = 'app/assets/ lib/assets vendor/assets'
changed_asset_count = capture("cd #{latest_release} && #{source.local.log(from)} #{asset_locations} | wc -l").to_i
rescue Exception => e
logger.info "Error: #{e}, forcing precompile"
force_compile = true
end
if changed_asset_count > 0 || force_compile
logger.info "#{changed_asset_count} assets have changed. Pre-compiling"
run %Q{cd #{latest_release} && #{rake} RAILS_ENV=#{rails_env} #{asset_env} assets:precompile}
else
logger.info "#{changed_asset_count} assets have changed. Skipping asset pre-compilation"
end
end
end
As i'm new to Rails, I made the mistake of using the default path ( /system/:attachment/:id/:style/:filename ) in 4 different models. Now, i would like to move each model to its own folder but without losing old data.
What is the proper way of handling this? Does Paperclip offer an option to automatically migrate data from old folders?
Thanks.
I had a similar dilemma. We were storing all our attachments in a certain path, and then business requirements changed and everything had to be moved and re-organized.
I'm surprised how little info there is on changing paperclip path and moving files. Maybe I'm missing the obvious?
Like Fernando I had to write a rake task. Here's what my code looks like (attachments model is Attachment, and the actual Paperclip::Attachment object is :file )
task :move_attachments_to_institution_folders => :environment do
attachments = Attachment.all
puts "== FOUND #{attachments.size} ATTACHMENTS =="
old_path_interpolation = APP_CONFIG[ 'paperclip_attachment_root' ] + "/:id_partition.:extension"
new_path_interpolation = APP_CONFIG[ 'paperclip_attachment_root' ] + "/:institution/reports/:id_:filename"
attachments.each do |attachment|
# the interpolate method of paperclip takes the symbol variables and evaluates them to proper path segments.
old_file_path = Paperclip::Interpolations.interpolate(old_path_interpolation, attachment.file, attachment.file.default_style) #see paperclip docs
puts "== Current file path: #{old_file_path}"
new_file_path = Paperclip::Interpolations.interpolate(new_path_interpolation, attachment.file, attachment.file.default_style)
if File.exists?(old_file_path)
if !File.exists?(new_file_path) #don't overwrite
FileUtils.mkdir_p(File.dirname(new_file_path)) #create folder if it doesn't exist
FileUtils.cp(old_file_path, new_file_path)
puts "==== File copied (^_^)"
else
puts "==== File already exists in new location."
end
else
puts "==== ! Real File Not Found ! "
end
end
The key thing for me was to have paperclip re-calculate the old path by using its default interpolations. From then it was just a matter of using standard FileUtils to copy the file over. The copy takes care of renaming.
P.S.
I'm on rails 2.3.8 branch, with paperclip -v 2.8.0
I ended up creating a small rake task to do this. Assuming that you have a model called User and your image file is called "image", place the following code in lib/tasks/change_users_folder.rb
desc "Change users folder"
task :change_users_folder => :environment do
#users = User.find :all
#users.each do |user|
unless user.image_file_name.blank?
filename = Rails.root.join('public', 'system', 'images', user.id.to_s, 'original', user.image_file_name)
if File.exists? filename
user.image = File.new filename
user.save
end
end
end
end
Them, run rake change_users_folder and wait.
Note that this won't delete old files. They will be kept at the original place and a copy will be created at the new folder. If everything went well, you can delete them later.
And for my future code, i will make sure i always set :path and :url when using paperclip :)
I feel like this should be a simple problem, but I'm pulling my hair out trying to track it down. I'm installed the chargify_api_ares gem, but can't do even basic things such as
Chargify::Subscription.create
As I get this path error. I feel like this must be a gem issue somehow but don't know where to go from here.
UPDATE: bundle show chargify_api_ares shows the correct path, I just somehow can't access it. Still trying random environment related things.
Looks like this is the source of the problem, in active_resource\base.rb:
# Gets the \prefix for a resource's nested URL (e.g., <tt>prefix/collectionname/1.json</tt>)
# This method is regenerated at runtime based on what the \prefix is set to.
def prefix(options={})
default = site.path
default << '/' unless default[-1..-1] == '/'
# generate the actual method based on the current site path
self.prefix = default
prefix(options)
end
As I understand it, Chargify.subdomain should be setting the site.path, but I don't understand activeresource well enough yet to know what's happening and will continue to dig.
I too had the same issue.
I executed the following on the console
Chargify.configure do |c|
c.api_key = "<<api_key>>"
c.subdomain = "<<subdomain>>"
end
After that performing any Chargify console commands went through fine.