Capistrano deploy assets precompile never compiles assets, why? - ruby-on-rails-3

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

Related

How to refresh Rails / Sprockets to be aware of new manifest on production server after assets:precompile

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

How to prevent initializers from running when running `rails generate`

I want to prepopulate my cache with an initializer, but I don't need this code to run every time I run rake or rails g, etc. Rake and Bundler are easy to deal with, but a similar solution does not work for the generators:
# config/initializers/prepop_cache.rb
if !defined?(::Bundler) and !defined?(::Rake) and !defined(Rails::Generators)
# do stuff
end
This must be because rails/generators (or something similar) is requireed at runtime. How can I check to see if the command being run is rails g xyz?
Update:
Two solutions can be found here: Rails 3 initializers that run only on `rails server` and not `rails generate`, etc
Still would like to know if it's possible in the manner I've tried above.
In Rails 3, what you're looking to do is conceivably possible, but in a hacky way. Here's how:
When you make a rails generate call, the callpath looks like this:
bin/rails is called, which eventually routes you to execute script/rails
script/rails is executed which requires rails/commands
rails/commands is loaded, which is the main point of focus.
Within rails/commands the code that runs for generate:
ARGV << '--help' if ARGV.empty?
aliases = {
"g" => "generate",
"c" => "console",
"s" => "server",
"db" => "dbconsole"
}
command = ARGV.shift # <= #1
command = aliases[command] || command
case command
when 'generate', 'destroy', 'plugin', 'benchmarker', 'profiler'
require APP_PATH
Rails.application.require_environment! # <= #2
require "rails/commands/#{command}" # <= #3
The points of interest are numbered above. Namely, that at point #1 the command that you're running is shifting off of ARGV. Which in your case means generate is going to be removed from the command line args.
At point #2 your environment gets loaded, at which point your initializers are going to be executed. And herein is the tough part - because nothing indicating a specific command has been loaded at this point (this occurs at #3) there is no information to determine a generator is being run!
Let's insert a script into config/initializer/debug.rb to see what is available if we ran rails generate model meep:
puts $0 #=> "script/rails"
puts ARGV #=> ["model", "meep"]
As you can see, there is no direct information that a generator is being run. That said, there is indirect information. Namely ARGV[0] #=> "model". Conceivably you could create a list of possible generators and check to see if that generator has been called on ARGV[0]. The responsible developer in me says this is a hack and may break in ways you'd not expect so I'd use this cautiously.
The only other option is to modify script/rails like you suggested -- which isn't too bad a solution, but would likely break when you upgrade to Rails 4.
In Rails 4, you've got more hope! By the time the application environment is being loaded, the generators namespace has already been loaded. This means that in an initializer you could do the following:
if defined? Rails::Generators #=> "constant"
# code to run if generators loaded
else
# code to run if generators not loaded
end

trying to upload files using a ruby rake task

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

Rails 3 + Paperclip: moving current data to another folder

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 :)

undefined method 'path' for nil:NilClass using chargify_api_ares gem

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.