Assets pipeline rails Heroku - ruby

Recently I upgraded my project to Rails 5 and I'm going crazy with the assets pipeline when trying to upload everything to Heroku.
The issue is the following: I have a collection of Ejercicios and, when u click on one of them, the app should show its information, including an image. The routes to the images are stored in my db like this img1: "ejercicios/abdominales/1_4_I1.bmp". That file, for example, would be on app/assets/images/ejercicios/abdominales/1_4_I1.bmp.
The related view show.html.haml prints the images like this: = image_tag(#ejercicio.img1) if #ejercicio.img1?.
It worked perfectly on local but not in production in Heroku, so read about the assets pipeline in order to make it work. So I changed my show.html.haml like this: = image_tag asset_path(#ejercicio.img1) if #ejercicio.img1? and I added the lines the tutorial mentions in Gemfile and application.rb. The executed bundle install and bundle exec rake assets:precompile RAILS_ENV=production, added the new 'public' folder to my git, committed and pushed my git, and finally pushed everything to heroku.
But it doesn't work, the 'alt' of the image is shown. Using the inspector I can see that the images in the html follow the normal url to the image and not the one with the fingerprint, so the helper asset_path seems not to be working properly.
Here's my production.rb in config/environments
KeepMeFit::Application.configure do
config.eager_load = true
config.cache_classes = true
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
config.serve_static_assets = true
config.assets.compress = true
config.assets.compile = true
config.assets.digest = falsenginx
config.force_ssl = true
config.i18n.fallbacks = true
config.active_support.deprecation = :notify
config.action_mailer.default_url_options = { :host => "http://keepmefit.herokuapp.com/"}
end
My 'application.rb' in 'config':
require File.expand_path('../boot', __FILE__)
require 'rails/all'
require 'will_paginate/array'
if defined?(Bundler)
Bundler.require(*Rails.groups(:assets => %w(development test)))
end
module KeepMeFit
class Application < Rails::Application
config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
config.i18n.default_locale = :es
config.encoding = "utf-8"
config.filter_parameters += [:password, :password_confirmation]
config.active_support.escape_html_entities_in_json = true
config.assets.enabled = true
config.serve_static_assets = true
config.assets.initialize_on_precompile = false
config.assets.version = '1.0'
end
end
And my Gemfile:
source 'https://rubygems.org'
ruby '2.3.3'
gem 'rails', '5.1.4'
group :development, :test do
gem 'sqlite3'
gem 'activemodel'
gem 'json'
gem 'rspec-rails'
gem 'guard-rspec'
gem 'rb-notifu'
# gem 'railroady'
end
gem 'rails_12factor', group: :production
group :production do
gem 'pg'
end
group :test do
gem 'capybara'
gem 'factory_girl_rails', '4.1.0'
gem 'launchy'
end
group :development do
gem 'annotate'
gem 'better_errors'
gem 'binding_of_caller'
gem 'meta_request'
end
group :assets do
gem 'sass-rails'
gem 'coffee-rails'
gem 'coffee-script-source', '1.8.0'
gem 'uglifier', '>= 1.0.3'
end
gem 'jquery-rails'
gem 'bcrypt', '~> 3.1.11', platforms: [:ruby, :x64_mingw, :mingw]
gem 'haml'
gem 'haml-rails'
gem 'bootstrap-sass'
require 'rbconfig'
gem 'wdm', '>= 0.1.0' if RbConfig::CONFIG['target_os'] =~ /mswin|mingw/i
gem 'modernizr-rails'
#gem "font-awesome-rails"
gem 'bootstrap-datepicker-rails'
gem 'tzinfo-data'
gem 'faker', '1.1.2'
gem 'will_paginate', '~> 3.1.0'
gem 'bootstrap-will_paginate'
gem 'turbolinks'
gem 'jquery-turbolinks'
gem 'friendly_id'
gem 'gon'
gem 'cloudinary'

The asset pipeline has basically two use-cases:
First, it precompiles and combines various stylesheets or javascript file into single bundles. Being able to precompile - for example - SCSS to CSS simplifies development. And one big combined files can be downloaded faster than many small files.
Second, it adds hashes to the filenames. This allows caching these files for a long time which improves performance too. Even if there is only a small change in one of the files then the hash and therefore the filename will change. The changed filename will not be in the cache and therefore the browser reloads the file immediately.
But in your case, your images are static anyway. There is no point precompiling images and adding hashes to files that are not supposed to change.
Therefore I would just put that images directly into the public folder and would bypass the asset pipeline for this kind of static images.

Related

Stale Asset - Hanami does not update the edited files

I'm using Hanami with sass as preprocessor, but when I make changes in some .scss file and refresh the page the changes don't load, the public/assets/file.css is not updating. For update I have to delete the file...
Does anyone know why this happens?
Gemfile
source 'https://rubygems.org'
gem 'bundler'
gem 'rake'
gem 'hanami', '0.7.3'
gem 'hanami-model', '~> 0.5'
gem "sass"
gem 'pg'
group :test do
gem 'minitest'
gem 'capybara'
end
group :production do
# gem 'puma'
end
application.rb
...
assets do
...
# Stylesheet compressor
#
# Supported engines:
#
# * :builtin
# * :yui
# * :sass
#
# See: http://hanamirb.org/guides/assets/compressors
#
# In order to skip stylesheet compression comment the following line
stylesheet_compressor :builtin
# Specify sources for assets
#
sources << [
'assets'
]
end
did you tried to upgrade to the latest Hanami version? As of today it's 0.9.2.

Rspec suite fails running on AWS Ubuntu with ECONNREFUSED - but each test passes individually

We are trying to migrate our rails build from a local network server to an AWS EC2 instance running Ubuntu. The test suite works fine on all the developers machines (combination of mac and ubuntu) and the old build server (linux) but refuses to pass on the amazon instance.
The symptom is:
An error occurred in an after hook
Errno::ECONNREFUSED: Connection refused - connect(2)
occurred at /home/ubuntu/.rvm/rubies/ruby-2.0.0-p481/lib/ruby/2.0.0/net/http.rb:878:in 'initialize'
which is repeated a bunch of times. There is no error logged before this one.
However this issue only occurs when running multiple tests together (eg, bundle exec rspec) - when I run each test individually they all pass. Locally none of the dev team have seen this issue before.
Our tests use Selenium and Firefox which should run headless on ubuntu using Xvfb. We also use WebMock for some tests.
I have researched this issue for a day or two now and tried everything I can think of, to no avail. I have checked the versions of firefox and all the gems installed are the same on aws as locally.
My gemfile and spec_helper are below. I have investigated the firefox and xvfb installation, but because each test is able to pass individually I feel the system is generally ok ... but clearly something is not happy.
Version details
ruby 2.0.0p481
rails 3.2.16
rspec 2.14.8
firefox 29
ubuntu 14.04
Gemfile
source 'https://rubygems.org'
#Base gems
gem 'rails', '~> 3.2.16'
gem 'sass-rails'
gem 'bcrypt-ruby', '~> 3.0.0'
gem 'faker', '~> 1.2.0'
gem 'jquery-rails', '~> 3.0.0'
#gem 'jquery-rails', '~> 2.1.4'
gem 'jquery-migrate-rails'
# threading gem
gem 'sucker_punch', '~> 1.0'
gem 'mixpanel-ruby'
# Mongo gems
gem 'mongoid', '~> 3.1.6'
gem 'bson_ext', '~> 1.9.2'
gem 'origin', '~> 1.1.0'
gem 'mongoid-enum' , '~> 0.1.1'
#filemaker gem
#gem 'ginjo-rfm', '~> 2.1.7'
# data gird gem
gem 'datagrid', '1.0.5'
# New Relic and Engine Yard Gems
gem 'ey_config', '~> 0.0.6'
gem 'newrelic_rpm'
#Authorsiation
gem 'cancan', '~> 1.6.10'
#paging
gem 'kaminari', '~> 0.15'
#client side validation
gem 'jquery-validation-rails'
#file upload
gem 'carrierwave-mongoid', :require => 'carrierwave/mongoid'
gem 'rmagick', '~> 2.13.2'
gem 'fog' , '~> 1.19.0'
gem 'unf', '~> 0.1.3'
gem 'remotipart', '~> 1.2'
gem 'listen', '2.7.6'
# reports for jenkins - see if having it here allows engineyard to deploy
gem 'ci_reporter', '1.9.1'
#NOTE YOU MUST INSTALL IMG MAGIC IF bundle install fails
#http://www.imagemagick.org/script/binary-releases.php#unix
#sudo apt-get install libmagickwand-dev imagemagick
gem 'timecop', '~> 0.7.1'
#file upload
gem 'jquery-fileupload-rails', '~> 0.4.1'
gem 'jquery-cookie-rails', '~> 1.3.1'
#configuring Rails
gem 'figaro'
#History tracking
gem 'mongoid-history'
gem 'nav_lynx'
#modal window requirements
gem 'jquery-ui-rails'
gem 'jquery-modal-rails'
gem 'itree'
gem 'lumberjack'
gem 'newrelic_moped'
group :development, :test do
gem 'rspec-rails', '~> 2.14.0'
gem 'guard-rspec', '~> 4.2.0'
gem 'guard-spork', '~> 1.5.1'
gem 'childprocess', '0.3.9'
gem 'spork', '~> 1.0.0rc4'
gem 'spork-rails', '~> 4.0.0'
gem 'bullet'
end
group :development, :staging do
gem 'rack-mini-profiler'
end
#Used to annotate model files generated
group :development do
gem 'annotate', '~> 2.6.0'
gem 'letter_opener', '~> 1.1.2'
end
# Gems used only for assets and not required
# in production environments by default.
group :assets do
gem 'coffee-rails', '~> 3.2.2'
gem 'uglifier', '~> 2.3.2'
end
group :test do
gem 'capybara', '~> 2.2.1'
gem 'selenium-webdriver', '2.39.0'
gem 'database_cleaner', '~> 1.2.0'
#needs sudo apt-get install xvfb
gem 'headless'
#static security analysis tool
gem 'brakeman', :require => false
#generating mock objects in tests
gem 'factory_girl_rails', '~> 4.3.0'
gem 'webmock', '~> 1.16.0'
#for windows
gem 'rb-fchange' if /win32/ =~ RUBY_PLATFORM
gem 'rb-notifu' if /win32/ =~ RUBY_PLATFORM
gem 'win32console' if /win32/ =~ RUBY_PLATFORM
#for linux
gem 'rb-inotify', '~> 0.9.2' if /linux/ =~ RUBY_PLATFORM
gem 'libnotify', '~> 0.8.2' if /linux/ =~ RUBY_PLATFORM
#for macosx
gem 'growl', '~> 1.0.3' if /darwin/ =~ RUBY_PLATFORM
gem 'rb-fsevent', '~> 0.9.3' if /darwin/ =~ RUBY_PLATFORM
# for rcov in Jenkins
gem 'simplecov'
gem 'simplecov-rcov'
#additional matches for rspect
gem 'shoulda-matchers', '~> 2.5.0'
#open browser on demand to debug tests
gem 'launchy'
#http rest client
gem 'rest-client', '~> 1.6.7'
gem 'show_me_the_cookies'
end
spec_helper.rb
require 'rubygems'
require 'spork'
require 'webmock/rspec'
require 'sucker_punch'
require 'sucker_punch/testing/inline'
Spork.prefork do
if ENV["RUBYMINE_HOME"]
$:.unshift(File.expand_path("rb/testing/patch/common", ENV["RUBYMINE_HOME"]))
$:.unshift(File.expand_path("rb/testing/patch/bdd", ENV["RUBYMINE_HOME"]))
end
# setup simple cov for Jenkins
require 'simplecov'
require 'simplecov-rcov'
SimpleCov.formatter = SimpleCov::Formatter::RcovFormatter
SimpleCov.start 'rails'
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'rspec/autorun'
# Requires supporting ruby files with custom matchers and macros, etc,
# in spec/support/ and its subdirectories.
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
RSpec.configure do |config|
config.include ShowMeTheCookies
# Include Factory Girl syntax to simplify calls to factories
config.include FactoryGirl::Syntax::Methods
#Don't run any tests that contain :skip_test => true
config.filter_run_excluding :skip_test => true
# If true, the base class of anonymous controllers will be inferred
# automatically. This will be the default behavior in future versions of
# rspec-rails.
config.infer_base_class_for_anonymous_controllers = false
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
config.order = "random"
config.include Capybara::DSL
config.before(:suite) do
Headless.new.start
end
config.before(:all) do
#manually clear database
YearDates.destroy_all
CoursePlan.destroy_all
Topic.destroy_all
FactoryGirl.create(:stub_year_dates)
end
config.after(:all) do
Timecop.return
end
#Mongoid database cleaner
config.before(:suite) do
DatabaseCleaner[:mongoid, {:connection => :unit_test}].clean_with(:truncation)
DatabaseCleaner[:mongoid, {:connection => :unit_test}].strategy = :truncation
end
config.before(:each) do
new_time = Time.local(2014, 1, 20) #week two of the year
Timecop.travel(new_time)
Timecop.baseline = new_time
DatabaseCleaner[:mongoid, {:connection => :unit_test}].start
FactoryGirl.create(:stub_year_dates) #recreate this on each test as it is needed all the time, but edited sometimes
#need to ensure these exist before the other factories are called
FactoryGirl.create(:english_subject)
FactoryGirl.create(:chemistry_subject)
FactoryGirl.create(:maths_ext_2_subject)
FactoryGirl.create(:maths_ext_1_tutorials_only_subject)
end
config.after(:each) do
Timecop.return_to_baseline
DatabaseCleaner[:mongoid, {:connection => :unit_test}].clean
end
Capybara.default_wait_time = 5 #wait longer for ajax requests
end
end
Spork.each_run do
# This code will be run each time you run your specs.
FactoryGirl.reload
end
WebMock.allow_net_connect!
I would greatly appreciate any assistance!
update
I have determined that the results are inconsistent between test runs. At first I thought it was the same each time, but the number of tests failing varies each run. I thought I had fixed the problem when all the tests passed except one, but the next run it was back to over a hundred failures.
update 2
Upon closer inspection (oops) I have discovered there were some tests failing with a different error the the majority. Instead of ECONNREFUSED, they are reporting 'End Of File Reached'. When I disabled these tests (5 in total) the remaining tests pass reliably. I suspect that xvfb is encountering some javascript or ajax related error, which is then preventing any of the following tests from passing. We are now working on diagnosing what is happening in these tests that is causing the failure.
File this one under 'not sure'. We ended up running up a new AWS server and setting it up again from scratch, and this time it worked fine. Some where suspect an issue with the javascript driver, possibly permissions related, but it is not worth our time investigating.

the irbrc config file doesn't work for ruby 2 + rails 4

The irbrc config file works on the rails 3.2 + ruby 1.9
Today I checked out a project, using rails 4 + ruby 2,
and I found it didn't load the .irbrc file (I put the file under my home directory)
When I ran into irb or rails console
What's the problem?
irbrc file
require 'irb/completion'
require 'hirb' ; Hirb.enable
ARGV.concat ["--readline", "--prompt-mode", "simple"]
IRB.conf[:SAVE_HISTORY] = 10000
IRB.conf[:HISTORY_FILE] = "#{ENV['HOME']}/.irb_history"
ActiveRecord::Base.logger.level = 1 # Avoid log in Rails console
ActiveRecord::Base.logger = Logger.new STDOUT #顯示 SQL statements
ActiveRecord::Base.connection.tables
def drop_tbl (tblname)
ActiveRecord::Migration.drop_table(eval(":"+tblname))
end
def show_tbls
tbls = ActiveRecord::Base.connection.tables
tbls.each { |tbl|
puts "#{tbl} #{tbl_name(tbl)}"
}
end
def tbl_name(name)
name.singularize.humanize.split().map{|x| x.capitalize}.join()
end
def cols (tblname)
cols = eval("#{tblname}.column_names")
ap(cols)
end
Gemfile in the project
source 'https://rubygems.org'
ruby '2.0.0'
gem 'bootstrap-sass'
gem 'coffee-rails'
gem 'rails'
gem 'haml-rails'
gem 'sass-rails'
gem 'uglifier'
gem 'jquery-rails'
group :development do
gem 'sqlite3'
gem 'pry'
gem 'pry-nav'
gem 'thin'
gem "better_errors"
gem "binding_of_caller"
end
group :production do
gem 'pg'
gem 'rails_12factor'
end
I believe the irb config file doesn’t get loaded in rails console if the file is erroneous. Run ruby ~/.irbrc to make sure that it evaluates without complaint. Additionally, you can verify that your console is even sourcing your irbrc by running $LOAD_PATH.index{|s| s.include?('irbrc')} within your console.
You're using Pry. Try renaming the file to .pryrc.

No rspec output in console for guard watched file

I have installed 'guard' and 'guard-rspec', I have also configured Guardfile (to watch changes in 'app/views' ) but when I run 'bundle exec guard' I always get this:
vagrant#vagrant-debian-squeeze:/vagrant/sample_app$ bundle exec guard
Guard could not detect any of the supported notification libraries.
Guard is now watching at '/vagrant/sample_app'
Guard::RSpec is running, with RSpec 2!
Running all specs
........
Finished in 0.97359 seconds
8 examples, 0 failures
>
It has finished with guard console prompt and if I edit some file from 'app/views/' (e.g. app/view/static_pages/home.html.erb) and save it, guard didn't display any spec output, just still wait for some console command.
I suppose it should display some rspec output after saving watched file.
Gemfile:
source 'https://rubygems.org'
gem 'rails', '3.2.3'
# Bundle edge Rails instead:
# gem 'rails', :git => 'git://github.com/rails/rails.git'
group :development, :test do
gem 'sqlite3', '1.3.5'
gem 'rspec-rails', '2.9.0'
gem 'guard-rspec', '0.5.5'
gem 'guard'
end
# Gems used only for assets and not required
# in production environments by default.
group :assets do
gem 'sass-rails', '3.2.4'
gem 'coffee-rails', '3.2.2'
# See https://github.com/sstephenson/execjs#readme for more supported runtimes
gem 'therubyracer'
gem 'uglifier', '1.2.3'
end
gem 'jquery-rails', '2.0.0'
group :test do
gem 'capybara', '1.1.2'
# gem 'rb-inotify', '0.8.8'
# gem 'libnotify', '0.5.9'
end
# To use ActiveModel has_secure_password
# gem 'bcrypt-ruby', '~> 3.0.0'
# To use Jbuilder templates for JSON
# gem 'jbuilder'
# Use unicorn as the app server
# gem 'unicorn'
# Deploy with Capistrano
# gem 'capistrano'
# To use debugger
# gem 'ruby-debug19', :require => 'ruby-debug'
Guardfile:
# A sample Guardfile
# More info at https://github.com/guard/guard#readme
require 'active_support/core_ext'
guard 'rspec', :version => 2, :all_after_pass => false do
watch(%r{^spec/.+_spec\.rb$})
watch(%r{^lib/(.+)\.rb$}) { |m| "spec/lib/#{m[1]}_spec.rb" }
watch('spec/spec_helper.rb') { "spec" }
# Rails example
watch(%r{^spec/.+_spec\.rb$})
watch(%r{^app/(.+)\.rb$}) { |m| "spec/#{m[1]}_spec.rb" }
watch(%r{^app/(.*)(\.erb|\.haml)$}) { |m| "spec/#{m[1]}#{m[2]}_spec.rb" }
watch(%r{^lib/(.+)\.rb$}) { |m| "spec/lib/#{m[1]}_spec.rb" }
watch(%r{^app/controllers/(.+)_(controller)\.rb$}) { |m| ["spec/routing/#{m[1]}_routing_spec.rb", "spec/#{m[2]}s/#{m[1]}_#{m[2]}_spec.rb", "spec/acceptance/#{m[1]}_spec.rb", (m[1][/_pages/] ? "spec/requests/#{m[1]}_spec.rb" : "spec/requests/#{m[1].singularize}_pages_spec.rb")]}
watch(%r{^spec/support/(.+)\.rb$}) { "spec" }
watch('spec/spec_helper.rb') { "spec" }
watch('config/routes.rb') { "spec/routing" }
watch('app/controllers/application_controller.rb') { "spec/controllers" }
# Capybara request specs
watch(%r{^app/views/(.+)/}) do |m|
"spec/requests/#{m[1].singularize}_pages_spec.rb"
end
end
Guard watch rule for 'app/views' is
watch(%r{^app/views/(.+)/}) do |m|
"spec/requests/#{m[1].singularize}_pages_spec.rb"
end
Runtime environment:
Debian-Squeeze 32bit Vagrant box
Btw. I'm learning a Rails form ruby-on-rails-tutorial-book and stuck at Automated tests with Guard
Any help is appreciate, thank you.
Guard doesn't pick up filesystems changes made by the Vagrant host (Ubuntu in my case).
You can pass the -p option to force guard to poll the filesystem (increases CPU usage, constantly hits the hard disk and can cause your laptop temperature to rise — so not ideal but it works)
bundle exec guard -p
Uncomment the notification library in your test group, so your Gemfile looks like.
group :test do
gem 'capybara', '1.1.2'
gem 'rb-inotify', '0.8.8'
gem 'libnotify', '0.5.9'
end
That ought to do it. Have fun with Rails Tutorial, it's great!
EDIT: That's assuming your running Linux. OS X and Windows have their own test libraries. Keep reading the Tutorial and you'll see it.
Try this instead (from the Guardfile generated by guard init):
watch(%r{^app/views/(.+)/}) { |m| "spec/requests/#{m[1]}_spec.rb" }
The regular expression is correct, but it seems something about the filename 'spec/requests/#{m[1].singularize}_pages_spec.rb' in the block causes guard to fail silently as if the expression hadn't matched. I have no idea why.
I have remove Guard and install Watchr and it seems that it makes his work correctly. This helped me out:
How to rails 3 and rspec 2

rails 3.1, why my coffee scripts not working?

I am trying to test coffee script in my rails 3.1 project, but it doesn't get executed, or generated as javascript in the application.js
I have a controller Page, here is the pages.js.coffee:
test = (input) ->
alert input
test 'hello'
but that alert never get executed at http://127.0.0.1:3000/pages,
in fact, the application.js is just empty!
here is the GemFile in case it would help:
source 'http://rubygems.org'
gem 'rails', '3.1.0'
# Bundle edge Rails instead:
# gem 'rails', :git => 'git://github.com/rails/rails.git'
gem 'sqlite3'
gem 'devise', '1.4.8'
gem 'will_paginate', '~> 3.0.2'
#gem 'nested_form', :git => 'git://github.com/fxposter/nested_form.git'
gem "simple_form"
gem 'kaminari'
gem 'foreigner'
gem "cocoon"
# Gems used only for assets and not required
# in production environments by default.
group :assets do
gem 'sass-rails', " ~> 3.1.0"
gem 'coffee-rails', "~> 3.1.0"
gem 'uglifier'
end
gem "jquery-rails"
gem 'coffee-script'
gem 'haml'
# Use unicorn as the web server
# gem 'unicorn'
# Deploy with Capistrano
# gem 'capistrano'
# To use debugger
# gem 'ruby-debug19', :require => 'ruby-debug'
group :test do
# Pretty printed test output
gem 'turn', :require => false
end
EDIT
I have added those gems also and installed them, but, the coffee script is not executed
gem 'therubyracer'
gem 'coffee-script-source'
gem 'json'
gem 'execjs'
First: Having "coffee-rails" in your :assets group should be enough. Older versions had "coffee-script" in the :assets group.
Second: Where are you keeping your *.js.coffee files? You need to make sure they are in an "assets" folder some place. Start with app/assets/javascripts. If they aren't in your assets folder, they won't make it into the asset pipeline.
If you are doing that already, consider starting a new project and use the default configuration. It should work without any trouble. Compare the working project against the non-working project.
If all else fails, is it possible for you to share your project with us on GitHub?
Please check your config/application.rb, you should find a section like this:
if defined?(Bundler)
# If you precompile assets before deploying to production, use this line
Bundler.require(*Rails.groups(:assets => %w(development test)))
# If you want your assets lazily compiled in production, use this line
#Bundler.require(:default, :assets, Rails.env)
end
I suspect you are not precompiling assets on deploy, even though you have it set to ignore the assets gems.

Resources