JRUBY - RAILS 3 - TOMCAT 7 Deploy failed - ruby

I have my rails 3 app. This work fine in netbeans with webrick.
I create this application with:
Jruby jruby 1.6.5.1 (ruby-1.8.7-p330)
Rails 3.1.3
My bundle work fine.
Mi gemfile:
gem 'rails', '3.1.3'
gem 'dynamic_form'
gem 'activerecord-jdbcmysql-adapter'
gem 'jruby-openssl'
gem 'json'
group :assets do
gem 'sass', '~> 3.1.12'
gem 'sass-rails', '~> 3.1.5'
gem 'coffee-rails', '~> 3.1.1'
gem 'uglifier', '>= 1.0.3'
end
gem 'jquery-rails'
For create .war file from application, I have installed with bundle all gem required.
I have installed wrable and run
wrable config
and then
wrable
This create the .war file.
I put this file on the webapps tomcat7 directory and start the server.
Server starting fine, catalina.out logs no errors but...
When I try to go at the address when tomcat manager says is my application, I have more time to attendo for view just a withe page. the application name is "cameraAccreditiGiornalisti". So, the address is localhost:8080/cameraAccreditiGiornalisti => white page!
I read all guides in the web but I not say where is the problem!! Not have a log to look and the white page... no error!
Please help!

I have the same problem, I found out that war file does not include web.xml file, which is necessary for Tomcat to start up the webapp. I did not found any info why warble does not generate that file, as it should.

my problem solved... I read a wrong log file.... Maybe for your problem check the file warble.rb in projectdirectory/config. This is my and work:
# Disable Rake-environment-task framework detection by uncommenting/setting to false
# Warbler.framework_detection = false
# Warbler web application assembly configuration file
Warbler::Config.new do |config|
# Features: additional options controlling how the jar is built.
# Currently the following features are supported:
# - gemjar: package the gem repository in a jar file in WEB-INF/lib
# - executable: embed a web server and make the war executable
# - compiled: compile .rb files to .class files
# config.features = %w(gemjar)
# Application directories to be included in the webapp.
config.dirs = %w(app config lib log vendor tmp)
# Additional files/directories to include, above those in config.dirs
# config.includes = FileList["db"]
# Additional files/directories to exclude
# config.excludes = FileList["lib/tasks/*"]
# Additional Java .jar files to include. Note that if .jar files are placed
# in lib (and not otherwise excluded) then they need not be mentioned here.
# JRuby and JRuby-Rack are pre-loaded in this list. Be sure to include your
# own versions if you directly set the value
# config.java_libs += FileList["lib/java/*.jar"]
# Loose Java classes and miscellaneous files to be included.
# config.java_classes = FileList["target/classes/**.*"]
#config.java_classes = FileList["log4j.properties"]
# One or more pathmaps defining how the java classes should be copied into
# the archive. The example pathmap below accompanies the java_classes
# configuration above. See http://rake.rubyforge.org/classes/String.html#M000017
# for details of how to specify a pathmap.
# config.pathmaps.java_classes << "%{target/classes/,}p"
# Bundler support is built-in. If Warbler finds a Gemfile in the
# project directory, it will be used to collect the gems to bundle
# in your application. If you wish to explicitly disable this
# functionality, uncomment here.
# config.bundler = false
# An array of Bundler groups to avoid including in the war file.
# Defaults to ["development", "test"].
# config.bundle_without = []
# Other gems to be included. If you don't use Bundler or a gemspec
# file, you need to tell Warbler which gems your application needs
# so that they can be packaged in the archive.
# For Rails applications, the Rails gems are included by default
# unless the vendor/rails directory is present.
# config.gems += ["activerecord-jdbcmysql-adapter", "jruby-openssl"]
# config.gems << "tzinfo"
config.gems += ["activerecord-jdbcmysql-adapter", "jruby-openssl"]
# Uncomment this if you don't want to package rails gem.
# config.gems -= ["rails"]
# The most recent versions of gems are used.
# You can specify versions of gems by using a hash assignment:
#
config.gems["rails"] = "3.2.1"
# You can also use regexps or Gem::Dependency objects for flexibility or
# finer-grained control.
# config.gems << /^merb-/
# config.gems << Gem::Dependency.new("merb-core", "= 0.9.3")
# Include gem dependencies not mentioned specifically. Default is
# true, uncomment to turn off.
# config.gem_dependencies = false
# Array of regular expressions matching relative paths in gems to be
# excluded from the war. Defaults to empty, but you can set it like
# below, which excludes test files.
# config.gem_excludes = [/^(test|spec)\//]
# Pathmaps for controlling how application files are copied into the archive
# config.pathmaps.application = ["WEB-INF/%p"]
# Name of the archive (without the extension). Defaults to the basename
# of the project directory.
# config.jar_name = "mywar"
# Name of the MANIFEST.MF template for the war file. Defaults to a simple
# MANIFEST.MF that contains the version of Warbler used to create the war file.
# config.manifest_file = "config/MANIFEST.MF"
# When using the 'compiled' feature and specified, only these Ruby
# files will be compiled. Default is to compile all \.rb files in
# the application.
# config.compiled_ruby_files = FileList['app/**/*.rb']
# === War files only below here ===
# Path to the pre-bundled gem directory inside the war file. Default
# is 'WEB-INF/gems'. Specify path if gems are already bundled
# before running Warbler. This also sets 'gem.path' inside web.xml.
# config.gem_path = "WEB-INF/vendor/bundler_gems"
# Files for WEB-INF directory (next to web.xml). This contains
# web.xml by default. If there is an .erb-File it will be processed
# with webxml-config. You may want to exclude this file via
# config.excludes.
# config.webinf_files += FileList["jboss-web.xml"]
# Files to be included in the root of the webapp. Note that files in public
# will have the leading 'public/' part of the path stripped during staging.
# config.public_html = FileList["public/**/*", "doc/**/*"]
# Pathmaps for controlling how public HTML files are copied into the .war
# config.pathmaps.public_html = ["%{public/,}p"]
# Value of RAILS_ENV for the webapp -- default as shown below
config.webxml.rails.env = ENV['RAILS_ENV'] || 'production'
# Application booter to use, one of :rack, :rails, or :merb (autodetected by default)
# config.webxml.booter = :rails
# Set JRuby to run in 1.9 mode.
# config.webxml.jruby.compat.version = "1.9"
# When using the :rack booter, "Rackup" script to use.
# - For 'rackup.path', the value points to the location of the rackup
# script in the web archive file. You need to make sure this file
# gets included in the war, possibly by adding it to config.includes
# or config.webinf_files above.
# - For 'rackup', the rackup script you provide as an inline string
# is simply embedded in web.xml.
# The script is evaluated in a Rack::Builder to load the application.
# Examples:
# config.webxml.rackup.path = 'WEB-INF/hello.ru'
# config.webxml.rackup = %{require './lib/demo'; run Rack::Adapter::Camping.new(Demo)}
# config.webxml.rackup = require 'cgi' && CGI::escapeHTML(File.read("config.ru"))
# Control the pool of Rails runtimes. Leaving unspecified means
# the pool will grow as needed to service requests. It is recommended
# that you fix these values when running a production server!
# config.webxml.jruby.min.runtimes = 2
# config.webxml.jruby.max.runtimes = 4
config.webxml.jruby.min.runtimes = 2
config.webxml.jruby.max.runtimes = 4
# JNDI data source name
# config.webxml.jndi = 'jdbc/rails'
end

Related

Why am I getting 502 Bad Gateway nginx/1.18.0 - Rails App on Elastic Beanstalk

I am trying to Run Rails App on AWS Elastic Beanstalk and although I was able to deploy the app successfully with green healthy instance and connect to created RDS. When I click the production link I am getting 502 Bad Gateway - nginx/1.18.0
I am scratching my head over this for some time now.
I am running Rails 6.0.3.5 with Puma Version 4.3.7 (ruby 2.6.6-p146)
Here's my production.rb :
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on Tiago's advice.
#config.consider_all_requests_local = true
config.action_controller.perform_caching = true
# Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"]
# or in config/master.key. This key is used to decrypt credentials (and other encrypted files).
# config.require_master_key = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress CSS using a preprocessor.
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
# config.assets.compile = false
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Store uploaded files on the local file system (see config/storage.yml for options).
config.active_storage.service = :local
# Mount Action Cable outside main process or domain.
# config.action_cable.mount_path = nil
# config.action_cable.url = 'wss://example.com/cable'
# config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
config.log_tags = [ :request_id ]
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Use a real queuing backend for Active Job (and separate queues per environment).
# config.active_job.queue_adapter = :resque
# config.active_job.queue_name_prefix = "quickroll_production"
config.action_mailer.perform_caching = false
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Use a different logger for distributed setups.
# require 'syslog/logger'
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
# Inserts middleware to perform automatic connection switching.
# The `database_selector` hash is used to pass options to the DatabaseSelector
# middleware. The `delay` is used to determine how long to wait after a write
# to send a subsequent read to the primary.
#
# The `database_resolver` class is used by the middleware to determine which
# database is appropriate to use based on the time delay.
#
# The `database_resolver_context` class is used by the middleware to set
# timestamps for the last write to the primary. The resolver uses the context
# class timestamps to determine how long to wait before reading from the
# replica.
config.force_ssl = false
#
# By default Rails will store a last write timestamp in the session. The
# DatabaseSelector middleware is designed as such you can define your own
# strategy for connection switching and pass that into the middleware through
# these configuration options.
# config.active_record.database_selector = { delay: 2.seconds }
# config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver
# config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session
end
And Puma.rb:
# The `threads` method setting takes two numbers: a minimum and maximum.
# Any libraries that use thread pools should be configured to match
# the maximum value specified for Puma. Default is set to 5 threads for minimum
# and maximum; this matches the default thread size of Active Record.
#
max_threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 }
min_threads_count = ENV.fetch("RAILS_MIN_THREADS") { max_threads_count }
threads min_threads_count, max_threads_count
# Specifies the `port` that Puma will listen on to receive requests; default is 3000.
#
port ENV.fetch("PORT") { 3000 }
# Specifies the `environment` that Puma will run in.
#
environment ENV.fetch("RAILS_ENV") { "development" }
# Specifies the `pidfile` that Puma will use.
pidfile ENV.fetch("PIDFILE") { "tmp/pids/server.pid" }
bind "unix:///var/run/puma/my_app.sock"
pidfile "/var/run/puma/my_app.sock"
# Specifies the number of `workers` to boot in clustered mode.
# Workers are forked web server processes. If using threads and workers together
# the concurrency of the application would be max `threads` * `workers`.
# Workers do not work on JRuby or Windows (both of which do not support
# processes).
#
# workers ENV.fetch("WEB_CONCURRENCY") { 2 }
# Use the `preload_app!` method when specifying a `workers` number.
# This directive tells Puma to first boot the application and load code
# before forking the application. This takes advantage of Copy On Write
# process behavior so workers use less memory.
#
# preload_app!
# Allow puma to be restarted by `rails restart` command.
plugin :tmp_restart
# bind "unix:///var/run/puma/my_app.sock"
# pidfile "/var/run/puma/my_app.sock"
My Gemfile looks like this:
git_source(:github) { |repo| "https://github.com/#{repo}.git" }
ruby '2.6.6'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 6.0.3', '>= 6.0.3.2'
# Use mysql as the database for Active Record
gem 'mysql2', '>= 0.4.4'
# Use Puma as the app server
gem 'puma', '~> 4.1'
# Use SCSS for stylesheets
# gem 'sass-rails', '>= 6'
# Transpile app-like JavaScript. Read more: https://github.com/rails/webpacker
gem 'webpacker', '~> 4.0'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.7'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 4.0'
# Use Active Model has_secure_password
# gem 'bcrypt', '~> 3.1.7'
# Use Active Storage variant
# gem 'image_processing', '~> 1.2'
# Reduces boot times through caching; required in config/boot.rb
gem 'bootsnap', '>= 1.4.2', require: false
gem 'font-awesome-sass'
#Devise Gem
gem 'devise'
#Pundit Gem
gem 'pundit'
gem "chartkick"
#Install figaro to manage local environment variables. Read more https://github.com/laserlemon/figaro
gem 'figaro'
#Install uickbooks ruby gem. Read more https://github.com/ruckus/quickbooks-ruby
gem 'quickbooks-ruby'
group :development, :test do
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
end
group :development do
# Access an interactive console on exception pages or by calling 'console' anywhere in the code.
gem 'web-console', '>= 3.3.0'
gem 'listen', '~> 3.2'
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring'
gem 'spring-watcher-listen', '~> 2.0.0'
end
group :test do
# Adds support for Capybara system testing and selenium driver
gem 'capybara', '>= 2.15'
gem 'selenium-webdriver'
# Easy installation and use of web drivers to run system tests with browsers
gem 'webdrivers'
end
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
gem 'prawn'
gem 'wicked_pdf'
gem 'wkhtmltopdf-binary'
gem 'xero-ruby'
gem 'sassc', '~> 2.1.0'
I have also created two extension files to install the bundler and Gems and to setup Node and Yarn
here's my Packages.config
# Install git in order to be able to bundle gems from git
packages:
yum:
git: []
patch: []
commands:
#01 && 02 needs for build native extension. See https://forums.aws.amazon.com/thread.jspa?messageID=550901&#550053
01_bundlerfix_command:
test: test ! -f /opt/elasticbeanstalk/containerfiles/.post-provisioning-complete
command: gem install rubygems-update -v '<3'
leader_only: false
02_update_rubygems:
test: test ! -f /opt/elasticbeanstalk/containerfiles/.post-provisioning-complete
command: $(which update_rubygems)
leader_only: false
# 03_bundlerfix_command:
# test: test ! -f /opt/elasticbeanstalk/containerfiles/.post-provisioning-complete
# command: gem install bundler -v 2.2.0
# leader_only: false
# Run rake with bundle exec to be sure you get the right version
add_bundle_exec:
test: test ! -f /opt/elasticbeanstalk/support/.post-provisioning-complete
cwd: /opt/elasticbeanstalk/hooks/appdeploy/pre
# 複数マッチ対応と上書き防止(後読み)
command: perl -pi -e 's/((?<!bundle exec )rake)/bundle exec $1/g' 11_asset_compilation.sh 12_db_migration.sh
# Bundle with --deployment as recommended by bundler docs
# cf. http://gembundler.com/v1.2/rationale.html under Deploying Your Application
add_deployment_flag:
test: test ! -f /opt/elasticbeanstalk/support/.post-provisioning-complete
cwd: /opt/elasticbeanstalk/hooks/appdeploy/pre
# 複数マッチ対応と上書き防止(先読み)
command: perl -pi -e 's/(bundle install(?! --deployment))/$1 --deployment/' 10_bundle_install.sh
# Vendor gems to a persistent directory for speedy subsequent bundling
make_vendor_bundle_dir:
test: test ! -f /opt/elasticbeanstalk/support/.post-provisioning-complete
command: mkdir -p /var/app/support/vendor_bundle
# Store the location of vendored gems in a handy env var
set_vendor_bundle_var:
test: test ! -f /opt/elasticbeanstalk/support/.post-provisioning-complete
cwd: /opt/elasticbeanstalk/support
command: sed -i '12iexport EB_CONFIG_APP_VENDOR_BUNDLE=$EB_CONFIG_APP_SUPPORT/vendor_bundle' envvars
# The --deployment flag tells bundler to install gems to vendor/bundle/, so
# symlink that to the persistent directory
symlink_vendor_bundle:
test: test ! -f /opt/elasticbeanstalk/support/.post-provisioning-complete
cwd: /opt/elasticbeanstalk/hooks/appdeploy/pre
command: sed -i 's/\(^cd $EB_CONFIG_APP_ONDECK\)/\1\nln -s $EB_CONFIG_APP_VENDOR_BUNDLE .\/vendor\/bundle/' 10_bundle_install.sh
# Don't run the above commands again on this instance
# cf. http://stackoverflow.com/a/16846429/283398
z_write_post_provisioning_complete_file:
cwd: /opt/elasticbeanstalk/support
command: touch .post-provisioning-complete
and yarn.config
01_node_get:
cwd: /tmp
command: 'sudo curl --silent --location https://rpm.nodesource.com/setup_6.x | sudo bash -'
02_node_install:
cwd: /tmp
command: 'sudo yum -y install nodejs'
03_yarn_get:
cwd: /tmp
# don't run the command if yarn is already installed (file /usr/bin/yarn exists)
test: '[ ! -f /usr/bin/yarn ] && echo "yarn not installed"'
command: 'sudo wget https://dl.yarnpkg.com/rpm/yarn.repo -O /etc/yum.repos.d/yarn.repo'
04_yarn_install:
cwd: /tmp
test: '[ ! -f /usr/bin/yarn ] && echo "yarn not installed"'
command: 'sudo yum -y install yarn'
The logs are quite vague to read however I have noticed I am getting 'upstream prematurely closed connection while reading response header from upstream, client:' right under /var/log/nginx/error.log
Hoping for some good steering into right direction here. Many thanks in Advance

Ruby Gem: Install configuration files to the user-home directory

I have to make a REST-Client in Ruby.
The client must be runnable from the command-line like a binary and also it must be "requirable" in a ruby script and provide different functions.
My gemspec does exactly what it should.
But i have no idea how to install a configuration file (YAML) in the user-home folder?
The config file should be in the user directory to provide easy access for the user.
Is this even possible?
Should i check on the first run if there is a config file and create it?
Can i execute an own installation routine while installing a gem?
I did exactly the same thing in Python and it worked fine, so the Ruby client should behave similar.
For such decisions, I wrote gem persey. If you look at the description of the use of this gem, you can see that it provides what you expect:
# Rails.root are not initialized here
app_path = File.expand_path('../../', __FILE__)
# ...
# config with secret keys
# you don't want store this config in repository and copy to secret folder on host machine
my_secret_key_config = '/home/user/secret/keys.yml'
# ...
# Persey.init ENV["environment"] do # set current environment
Persey.init Rails.env do # set current environment
source :yaml, my_secret_key_config, :secret # no comments. It's secret!
env :production do
# ...
end
env :development, :parent => :production do
# ...
end
end

How disable assets compilation on heroku?

I'm trying to deploy my rails app to heroku using this turtorial:
https://devcenter.heroku.com/articles/getting-started-with-rails4
So, I use rails 4.1.1 and ruby 2.1.1
My Gemfile has gem 'rails_12factor', group: :production inside.
My application.rb:
require File.expand_path('../boot', __FILE__)
require 'rails/all'
Bundler.require(*Rails.groups)
module Charticus
class Application Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
end
end
I created file public/assets/manifest.yml
But when I deploy app to heroku - it compile all my js-files files to application.js and all css-files application.css. And I can't see it on app.heroku.com using firebug.
What I need to do with my configurations to see all my js and css files on app.heroku.com ?
How disable assets precompiling and minification on heroku?
Help me please!
Thanks
lib/tasks/assets.rake
Rake::Task["assets:precompile"].clear
namespace :assets do
task 'precompile' do
puts "Not pre-compiling assets..."
end
end
You are done.
I compare config/environments/development.rb and config/environments/production.rb.
And make production.rb asset configs like in development.rb:
Comment this lines:
config.serve_static_assets = false
config.assets.js_compressor = :uglifier
config.assets.compile = false
config.assets.digest = true
Then:
Push my changes to git repo git push origin master
Push changes to heroku git push heroku master
Rails 4 applications have a manifest-*.json file, not a manifest.yml file. This file is typically generated when you run rake assets:precompile , how are you compiling your assets?
Regardless, you need a file public/assets/manifest-(fingerprint).json file
Fast forward to 2018, and you would need to add the following to config/initializers/production.rb:
config.assets.enabled = false
Then you'd need to customize Heroku's Ruby Buildpack to not run the assets:precompile rake task. I won't provide a link to such a buildpack because I won't support or warrant one, but its pretty easy to find it in lib/language_pack/ruby.rb and start removing relevant code.
You'd then have to configure your Heroku app to use your new forked Buildpack instead of the default one (e.g. using heroku buildpacks).
Thats the cleanest way to disable the asset pipeline in a Heroku app w/ Rails, without resorting to overriding Rails' built-in rake tasks.
Fast forward to 2021 and Rails 6.x, if you completely removed Webpacker and Sprockets/Asset Pipeline, replace the bin/yarn file content with something like:
#!/usr/bin/env ruby
puts 'Yarn not present, nothing to do.'
#danielricecodes's advice is probably still valid but way more invasive.

Accessing files packaged into a Ruby Gem

I have a Buildr extension that I'm packaging as a gem. I have a collection of scripts that I want to add to a package. Currently, I have these scripts stored as a big text block that I'm writing to file. I would prefer to have individual files that I can either copy directly or read/write back out. I would like these files to be packaged into the gem. I don't have a problem packaging them in (just stick them in the file system before rake install) but I can't figure out how to access them. Is there a Gem Resources bundle type thing?
There are basically two ways,
1) You can load resources relative to a Ruby file in your gem using __FILE__:
def path_to_resources
File.join(File.dirname(File.expand_path(__FILE__)), '../path/to/resources')
end
2) You can add arbitrary paths from your Gem to the $LOAD_PATH variable and then walk the $LOAD_PATH to find resources, e.g.,
Gem::Specification.new do |spec|
spec.name = 'the-name-of-your-gem'
spec.version ='0.0.1'
# this is important - it specifies which files to include in the gem.
spec.files = Dir.glob("lib/**/*") + %w{History.txt Manifest.txt} +
Dir.glob("path/to/resources/**/*")
# If you have resources in other directories than 'lib'
spec.require_paths << 'path/to/resources'
# optional, but useful to your users
spec.summary = "A more longwinded description of your gem"
spec.author = 'Your Name'
spec.email = 'you#yourdomain.com'
spec.homepage = 'http://www.yourpage.com'
# you did document with RDoc, right?
spec.has_rdoc = true
# if you have any dependencies on other gems, list them thusly
spec.add_dependency('hpricot')
spec.add_dependency('log4r', '>= 1.0.5')
end
and then,
$LOAD_PATH.each { |dir| ... look for resources relative to dir ... }

rake assets:precompile is slow

The command "rake assets:precompile" works very slow for me. Especially on my Amazon EC2 Micro production server which does not have a lot of processor resources. On EC2 I have to wait 1 minute or more during each deployment just for this precompile task alone. Is there a way to make it faster?
Previously I used Jammit to compress/minify css and js. Jammit worked nearly 10 times faster on the same web site and servers.
If you don't need to load the Rails environment, you should disable that with:
config.assets.initialize_on_precompile = false
EDIT: I've just written a gem to solve this problem, called turbo-sprockets-rails3. It speeds up your assets:precompile by only recompiling changed files, and only compiling once to generate all assets.
It would be awesome if you could help me test out the turbo-sprockets-rails3 gem, and let me know if you have any problems.
There is a bug in Rails 3.1.0 that includes too many files in the precompile process. This could be the reason for the slowness if you have many assets js and css assets.
The other is that Sprockets (the gem doing the compilation) is more complex and has to allow for more options - scss, coffeescript and erb. Because of this I suspect it will be slower doing just concatenation and minification.
As suggested, you could precompile the files before deploying them if this is still an issue.
My solution is to exclude application.js .css and any other application related assets from from precompilation. So that i can use rake assets:precompile once to precompile engine related assets only.
Then on each deploy i use a simple rake task to build any application related assets and merge them into manifest.yml:
namespace :assets do
task :precompile_application_only => :environment do
require 'sprockets'
# workaround used also by native assets:precompile:all to load sprockets hooks
_ = ActionView::Base
# ==============================================
# = Read configuration from Rails / assets.yml =
# ==============================================
env = Rails.application.assets
target = File.join(::Rails.public_path, Rails.application.config.assets.prefix)
assets = YAML.load_file(Rails.root.join('config', 'assets.yml'))
manifest_path = Rails.root.join(target, 'manifest.yml')
digest = !!Rails.application.config.assets.digest
manifest = digest
# =======================
# = Old manifest backup =
# =======================
manifest_old = File.exists?(manifest_path) ? YAML.load_file(manifest_path) : {}
# ==================
# = Compile assets =
# ==================
compiler = Sprockets::StaticCompiler.new(env,
target,
assets,
:digest => digest,
:manifest => manifest)
compiler.compile
# ===================================
# = Merge new manifest into old one =
# ===================================
manifest_new = File.exists?(manifest_path) ? YAML.load_file(manifest_path) : {}
File.open(manifest_path, 'w') do |out|
YAML.dump(manifest_old.merge(manifest_new), out)
end
end
end
To specify which assets to compile i use a YAML configuration file (config/assets.yml):
eg.
---
- site/site.css
- admin/admin.css
- site/site.js
- admin/admin.js

Resources