How to set log_level for the assets:precompile task? - ruby-on-rails

There is a method Rake::SprocketsTask#log_level= (defined by sprockets-3.7.1/lib/rake/sprocketstask.rb) but how to call it?
Rafael França says:
To change the logger you can define your own precompile tasks and
setting logger=
Rake::SprocketsTask.new do |t|
t.logger = Logger.new("log/assets.log")
end
I tried that (with log_level) and it returns a SprocketsTask instance, but how do I replace the assets:precompile task?
I want to set the log_level of the assets:precompile task to something quieter, like :warn.

some feedback, logger is an attribute of the class SprocketsTask.
require 'logger'
module Rake
# Simple Sprockets compilation Rake task macro.
#
# Rake::SprocketsTask.new do |t|
# t.environment = Sprockets::Environment.new
# t.output = "./public/assets"
# t.assets = %w( application.js application.css )
# end
#
class SprocketsTask < Rake::TaskLib
# Logger to use during rake tasks. Defaults to using stderr.
#
# t.logger = Logger.new($stdout)
#
attr_accessor :logger
I did not find the info in the api, there is some good explanation in the Rails Guide about the Log4r logger used by rails.
This is the explanation of the code you included
Rails makes use of the ActiveSupport::Logger class to write log information. Other loggers, such as Log4r, may also be substituted.
You can specify an alternative logger in config/application.rb or any other environment file, for example:
config.logger = Logger.new(STDOUT)
config.logger = Log4r::Logger.new("Application Log")
That command creates a log file by default under Rails.root/log/
The info you need are about log levels
When something is logged, it's printed into the corresponding log if the log level of the message is equal to or higher than the configured log level. If you want to know the current log level, you can call the Rails.logger.level method.
The available log levels are: :debug, :info, :warn, :error, :fatal, and :unknown, corresponding to the log level numbers from 0 up to 5, respectively. To change the default log level, use
config.log_level = :warn # In any environment initializer, or
Rails.logger.level = 0 # at any time
This is the Log4r::Logger.rb class.
It has attr_reader for :level, which is set with the def initizialize.
module Log4r
# See log4r/logger.rb
class Logger
attr_reader :name, :fullname, :path, :level, :parent
attr_reader :additive, :trace, :outputters
# Logger requires a name. The last 3 parameters are:
#
# level:: Do I have a level? (Otherwise, I'll inherit my parent's)
# additive:: Am I additive?
# trace:: Do I record the execution trace? (slows things a wee bit)
def initialize(_fullname, _level=nil, _additive=true, _trace=false)
# validation
raise ArgumentError, "Logger must have a name", caller if _fullname.nil?
Log4rTools.validate_level(_level) unless _level.nil?
validate_name(_fullname)
# create the logger
#fullname = _fullname
#outputters = []
#additive = _additive
deal_with_inheritance(_level)
LoggerFactory.define_methods(self)
self.trace = _trace
Repository[#fullname] = self
end
You can set the level by doing:
Log4r::Logger.new('Assets Log', :warn)
So I believe t.logger.level = 2 should set the level to :warn
Rake::SprocketsTask.new do |t|
t.logger = Logger.new("log/assets.log")
t.logger.level = 2
end
:debug, :info, :warn, :error, :fatal, and :unknown, corresponding to the log level numbers from 0 up to 5, respectively.
Also this works because, Log4r::Logger has a method def level=(_level) to re-set the level attribute.
# Set the logger level dynamically. Does not affect children.
def level=(_level)
Log4rTools.validate_level(_level)
#level = _level
LoggerFactory.define_methods(self)
Logger.log_internal {"Logger '#{#fullname}' set to #{LNAMES[#level]}"}
#level
end

Related

How do I get Rails to load my test envionrment variables when I run tests?

I'm using Rails 5. I have this file, config/environment_variables.yml
development:
COINBASE_KEY: devkey
COINBASE_SECRET: devsecret
test:
COINBASE_KEY: testkey
COINBASE_SECRET: testsecret
production:
COINBASE_KEY: prodkey
COINBASE_SECRET: prodsecret
I load it with the file, config/initializers/environment_variables.rb
module EnvironmentVariables
class Application < Rails::Application
config.before_configuration do
env_file = Rails.root.join("config", 'environment_variables.yml').to_s
if File.exists?(env_file)
YAML.load_file(env_file)[Rails.env].each do |key, value|
ENV[key.to_s] = value
end # end YAML.load_file
end # end if File.exists?
end # end config.before_configuration
end # end class
end # end module
but when I run my test using
rails test test/services/crypto_currency_service_test.rb
The test variables aren't loading -- rather those from the dev environment are loading. Below is my test file
require 'coinbase/wallet'
require 'minitest/mock'
class CryptoCurrencyServiceTest < ActiveSupport::TestCase
test 'sell' do
last_transaction = MyTransaction.new({
:transaction_type => "buy",
:amount_in_usd => "100",
:btc_price_in_usd => "3000"
})
puts "env: #{ENV['COINBASE_KEY']}"
#client = Coinbase::Wallet::Client.new(api_key: ENV['COINBASE_KEY'], api_secret: ENV['COINBASE_SECRET'])
How do I get the test variables to load by default when I run tests?
Edit: Here's the config/environments/test.rb file, which I haven't (consciously) changed ...
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# The test environment is used exclusively to run your application's
# test suite. You never need to work with it otherwise. Remember that
# your test database is "scratch space" for the test suite and is wiped
# and recreated between test runs. Don't rely on the data there!
config.cache_classes = true
# Do not eager load code on boot. This avoids loading your whole application
# just for the purpose of running a single test. If you are using a tool that
# preloads Rails for running tests, you may have to set it to true.
config.eager_load = false
# Configure public file server for tests with Cache-Control for performance.
config.public_file_server.enabled = true
config.public_file_server.headers = {
'Cache-Control' => 'public, max-age=3600'
}
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Raise exceptions instead of rendering exception templates.
config.action_dispatch.show_exceptions = false
# Disable request forgery protection in test environment.
config.action_controller.allow_forgery_protection = false
config.action_mailer.perform_caching = false
# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
config.action_mailer.delivery_method = :test
# Print deprecation notices to the stderr.
config.active_support.deprecation = :stderr
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
end
I would not recommend to write custom code for this. There are existing solutions for setting up environment variables. See dotenv-rails for example. It allows you to put common variables into .env file. Just add gem 'dotenv-rails' to your Gemfile and put common variables into .env file:
# .env
COINBASE_KEY: devkey
COINBASE_SECRET: devsecret
If you need environment-specific variables it allows you to have separate files for this: .env.development, .env.test and .env.production:
#.env.test
COINBASE_KEY: testkey
COINBASE_SECRET: testsecret
#.env.production
COINBASE_KEY: prodkey
COINBASE_SECRET: prodsecret
From the comments in your original post, I suggest checking if config.before_configuration block is not at fault. Might be the case that the rails environment is loaded after that block has run and so you get Rails.env == 'test' when you print that out inside a test, but in the configuration it takes keys from default (development) environment.
Might I suggest moving this part
env_file = Rails.root.join("config", 'environment_variables.yml').to_s
if File.exists?(env_file)
YAML.load_file(env_file)[Rails.env].each do |key, value|
ENV[key.to_s] = value
end # end YAML.load_file
end # end if File.exists?
out in an intializer and then check the environment variables. Might fix the problem. (because initializers surely should respect the environment)
UPDATE: From the documentation it seems that before_configuration block is the VERY first block config part to run, so Rails.env is probably not yet set at that point.

Modify Rails i18n config during a test?

I'm trying to test a Rails plugin to make sure that the correct action is performed with or without fallbacks turned on. Inside my Dummy application's configuration, I have:
module Dummy
class Application < Rails::Application
config.i18n.fallbacks = true
end
end
How can I flip this back to false for a specific test? So far I have tried:
Dummy::Application.config.i18n.fallbacks = false
Dummy::Application.configure do |app|
app.config.i18n.fallbacks = false
end
Rails.application.config.i18n.fallbacks = false
All to no avail.
This is an interesting question, actually once the app got initialized in the beginning, you couldn't change i18n configuration because it already got memoized with these codes:
# Setup i18n configuration.
def self.initialize_i18n(app)
return if #i18n_inited
...
#i18n_inited = true
end
And I18n.fallbacks was set with this line
I18n.fallbacks = I18n::Locale::Fallbacks.new(*args)
When you specify the callbacks as true, I18n.fallbacks has a value of
[1] pry(main)> I18n.fallbacks
=> {}
[2] pry(main)> I18n.fallbacks.class
=> I18n::Locale::Fallbacks
And I18n.fallbacks is used in this way:
locales.concat(I18n.fallbacks[I18n.locale]) if I18n.respond_to? :fallbacks
As long as I18n.respond_to? :fallbacks, the app will always have fallbacks feature turned on.
The method is defined here in I18n:
def fallbacks
##fallbacks ||= I18n::Locale::Fallbacks.new
end
To turn off the fallbacks feature, the only way is to make I18n.respond_to? :fallbacks return false.
Here you go:
class << I18n
remove_method :fallbacks
end

View Resque log output in Rails server logs

I've got a Rails 4 app on a Puma server with Resque/Resque-Scheduler running background jobs. What I'd like to know is how I merge the log output of my two Resque workers into my server log, or, of that is not possible, how I can view the log output of my Resque workers. Currently I have not been able to figure out how to view the log output for the workers, so I have no idea what's happening under the hood. I found this blogpost, which suggests adding the following likes to my resque.rake file:
task "resque:setup" => :environment do
Resque.before_fork = Proc.new {
ActiveRecord::Base.establish_connection
# Open the new separate log file
logfile = File.open(File.join(Rails.root, 'log', 'resque.log'), 'a')
# Activate file synchronization
logfile.sync = true
# Create a new buffered logger
Resque.logger = ActiveSupport::BufferedLogger.new(logfile)
Resque.logger.level = Logger::INFO
Resque.logger.info "Resque Logger Initialized!"
}
end
That didn't work. I also tried the suggestion in the comments, which was to replace Resque.logger = ActiveSupport::BufferedLogger.new(logfile) with Resque.logger = ActiveSupport::Logger.new(logfile), however that didn't work either. With the second option, I still get a NoMethodError: undefined method 'logger=' for Resque:Module error when I try to boot up a worker.
Here is my current resque.rake file:
require 'resque/tasks'
require 'resque_scheduler/tasks'
namespace :resque do
puts "Loading Rails environment for Resque"
task :setup => :environment do
require 'resque'
require 'resque_scheduler'
require 'resque/scheduler'
require 'postman'
end
end
I've looked at the Resque docs on logging, but am not sure how to use what's there as I admittedly don't know very much about logging in Rails. I haven't had any luck finding other useful resources on the subject.
How I fix it, it is not perfect but just works.
my environment: rails 5.0.1, resque: 1.26.0
at the first time, I set the Resque.logger and Resque.logger.level in config/initializers/resque.rb as most docs suggest:
# config/initializers/resque.rb
Resque.logger = Logger.new("#{Rails.root}/log/resque.log")
Resque.logger.level = Logger::DEBUG
then in the job, I output log by Resque.logger.info:
# update_xxx_job.rb
class UpdateXxxJob
def self.perform
Resque.logger.info 'Job starts'
...
end
end
it doesn't work, I can see nothing in log/resque.log.
then someone said should set the logfile sync always, no buffer, so I update the config/initializers/resque.rb according a question from stackoverflow:
# config/initializers/resque.rb
logfile = File.open(File.join(Rails.root, 'log', 'resque.log'), 'a')
logfile.sync = true
Resque.logger = ActiveSupport::Logger.new(logfile)
Resque.logger.level = Logger::INFO
still doesn't work.
I also tried config resque logger in lib/tasks/resque.rake:
# lib/tasks/resque.rake
require 'resque'
require 'resque/tasks'
require 'resque/scheduler/tasks'
require 'resque-scheduler'
require 'resque/scheduler/server'
namespace :resque do
task setup: :environment do
Resque.schedule = YAML.load_file(Rails.root + "config/resque_scheduler_#{Rails.env}.yml")
Resque.redis.namespace = "xxx_#{Rails.env}"
Resque.logger = Logger.new("#{Rails.root}/log/resque.log")
Resque.logger.level = Logger::INFO
end
end
doesn't work.
finally, I decide to move the logger configuration from initializer to the job, so the job now looks like:
# update_xxx_job.rb
class UpdateXxxJob
def self.perform
Resque.logger = Logger.new("#{Rails.root}/log/resque.log")
Resque.logger.level = Logger::DEBUG
Resque.logger.info 'Job starts'
...
end
end
then I can get what I want in the log/resque.log.
you can try it.
I've had the same problem while setting up mine. Here's what I did:
Resque.before_fork do
# Your code here
end
It seems before_fork accepts a block as an argument rather than assigning a block to it.
I faced the same issue so that I check the source of resque and finally I needed to do the followings at initialization process:
define log formatter.
then define logger with log-file path.
set any log level.
Here the example is at my config/initializers/resque.rb in rails case:
...
Resque.logger = Logger.new("#{Rails.root}/log/resque.log")
Resque.logger.level = Logger::DEBUG
Resque.logger.formatter = ::Logger::Formatter.new # This is important
Resque default logger formatter is set here and its definitions is here. That apparently just ignores the output...

"Unable to autoload constant User" error when changed code in development

I have a problem with my rails application. After an Update from Rails 3 to 4.
When I surf through the pages after starting the server in development mode everything is fine.
But after a single code change (even adding a space) every page request shows the following error.
Unable to autoload constant User, expected
/path/to/my/rails-app/app/models/user.rb to define it
The file lives exactly there and defines the class:
class User < ActiveRecord::Base
…
I tried many things with config.autoload_paths and config.eager_load_paths in application.rb but with no luck.
Deactivating spring did not help either.
Developing an app and having to restart the server after every single change seems so 90s.
$ rails -v
Rails 4.2.4
$ ruby -v
ruby 2.1.7p400 (2015-08-18 revision 51632) [x86_64-linux]
Some relevant configs:
development.rb
MyApp::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the webserver when you make code changes.
config.cache_classes = false
# Do not eager load code on boot. This avoids loading your whole application
# just for the purpose of running a single test. If you are using a tool that
# preloads Rails for running tests, you may have to set it to true.
config.eager_load = false
# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger
config.active_support.deprecation = :log
# Only use best-standards-support built into browsers
config.action_dispatch.best_standards_support = :builtin
# Do not compress assets
config.assets.compress = false
# Expands the lines which load the assets
config.assets.debug = true
config.action_mailer.delivery_method = :test
config.action_mailer.default_url_options = {
host: 'localhost',
port: 3000
}
end
application.rb
module Serviceportal
class Application < Rails::Application
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
[… some asset precompile stuff …]
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = 'utf-8'
# Custom directories with classes and modules you want to be autoloadable.
config.autoload_paths += Dir["#{config.root}/app/mailers",
"#{config.root}/app/controllers/concerns",
"#{config.root}/app/models/concerns",
"#{config.root}/app/decorators/concerns",
"#{config.root}/lib",
"#{config.root}/lib/shared"
]
config.eager_load_paths += Dir["#{config.root}/app/mailers",
"#{config.root}/app/controllers/concerns",
"#{config.root}/app/models/concerns",
"#{config.root}/app/decorators/concerns",
"#{config.root}/lib",
"#{config.root}/lib/shared"]
# 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 = 'Berlin'
# 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
[… some SQL and active support stuff …]
config.action_controller.include_all_helpers = false
config.action_controller.action_on_unpermitted_parameters = :raise
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
end
end
Edit: The error mostly shows up in lib/auth/user_proxy.rb in the following function. Maybe this helps to narrow the range of possible causes.
def self.usertype_allowed?(type)
[ User, TempCustomer ].include? type.classify.safe_constantize rescue false
end
Edit 2: Stringify the class names in Edit 1 helped (thanks #Benjamin Sinclaire). But only leads to the next errors. I could also avoid using classes. But at the following error in app/controllers/concerns/security.rb there is nothing can change?
Unable to autoload constant User, expected
/path/to/my/rails-app/app/models/user.rb to define it
code:
def set_current_user
User.current = current_user
end
with current user saved in the Thread (code from /path/to/my/rails-app/app/models/user.rb
def self.current
Thread.current['current_user']
end
def self.current=(user)
Thread.current['current_user'] = user
end
Just to make it clear again: It works after server restart in development until I change some code somewhere.
1 See if you have any multiple-level class or module declaration done one one line and change them to be declared in several lines.
Instead of
class Parent::Sub::Child
end
Do
module Parent
module Sub
class Child
end
end
end
2 Check your model association definitions, and ensure you are never using constant. Use string instead.
Instead of
belongs_to :manager, class_name: User
Do
belongs_to :manager, class_name: 'User'
3 Just saw your edit. Can you refactor like this?
# I assume `type` is a string or such, so we can compare classes
# names instead of constants, and get rid of `safe_constantize`
def self.usertype_allowed?(type)
['User', 'TempCustomer'].include? type.classify rescue false
end
4 Not a good idea to serialize an active record object in the Thread storage. Change it to store the user id instead, like this:
def set_current_user
User.current = current_user.id
end
def self.current
Thread.current['current_user_id']
end
def self.current=(user_id)
Thread.current['current_user_id'] = user_id
end
You don't need include app/models/concerns and app/controllers/concerns in your autoload/ eagerload paths as they are included by default in Rails 4: https://signalvnoise.com/posts/3372-put-chubby-models-on-a-diet-with-concerns
Also make sure that your concerns are defined as modules, extend ActiveSupport::Concern and with the appropriate file name
#taggable.rb
module Taggable
extend ActiveSupport::Concern
end
Another cause of your problem might be that some modules/ classes in app/decorators/concerns, lib, lib/shared are using the User class
which is not loaded yet or some of it's dependencies are not loaded so try adding require_relative path_to_user.rb at the top of those files
-----Edit-------
Try adding at the top of lib/auth/user_proxy.rb
require_dependency 'app/models/user'
This way you'll remove any ambiguity in autoloading the User class and you won't mess around with Rails autoloading see more here: http://guides.rubyonrails.org/autoloading_and_reloading_constants.html#require-dependency , http://guides.rubyonrails.org/autoloading_and_reloading_constants.html#common-gotchas
Same problem but in an engine w/ namespaces. No issues in production or in development until a code-change / autoload.
The solution was to
checking for double definitions (there were none)
checking if the module nesting strictly follows rails conventions in the filesystem.
I've had myns under myengine/app/myns/subns/obj.rb but myns is being ignored as it is at the root of the app folder, so moving the myns folder into a subfolder myengine/app/lib/myns solved the issue.
Note: the rails error message was very explicit about the module nesting (while still pointing to the wrong .rb file in the filesystem) so look closely at the error. The error was 'Unable to autoload constant subns/obj.rb in .../myns/subns/obj.rb'. Rails suggesting the incorrect file-location (which exists) is misleading in this case.
During a Rails/Ruby Update I found time to look into this and finally found the cause.
The user class had an unloadable in it for years. That caused the problems since Rails 4. Now I removed this and found no issues after that.

Rails not loading environment.rb correctly

I recently upgraded my application from Rails version 2.1.2 to version 2.2.2. It was tested in on development and on my staging system. When I moved to production it fails to load all the way through the environment.rb file. (Why, oh why, is it always on production!?!)
Below is my environment.rb file
# Be sure to restart your web server when you modify this file.
# Uncomment below to force Rails into production mode when
# you don't control web/app server and can't set it the proper way
# ENV['RAILS_ENV'] ||= 'production'
# Specifies gem version of Rails to use when vendor/rails is not present
#RAILS_GEM_VERSION = '2.1.0' unless defined? RAILS_GEM_VERSION
RAILS_GEM_VERSION = '2.2.2' unless defined? RAILS_GEM_VERSION
puts "loading rails..."
# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')
puts "require boot file"
require 'socket'
puts "require socket"
Rails::Initializer.run do |config|
puts "inside config section"
# Settings in config/environments/* take precedence over those specified here
# Skip frameworks you're not going to use (only works if using vendor/rails)
# config.frameworks -= [ :action_web_service, :action_mailer ]
# Only load the plugins named here, by default all plugins in vendor/plugins are loaded
# config.plugins = %W( exception_notification ssl_requirement )
# Add additional load paths for your own custom dirs
# config.load_paths += %W( #{RAILS_ROOT}/extras )
# Force all environments to use the same logger level
# (by default production uses :info, the others :debug)
# config.log_level = :debug
# Use the database for sessions instead of the file system
# (create the session table with 'rake db:sessions:create')
config.action_controller.session_store = :active_record_store
puts "setting session store type"
# Use SQL instead of Active Record's schema dumper when creating the test database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
# config.active_record.schema_format = :sql
# Activate observers that should always be running
# config.active_record.observers = :cacher, :garbage_collector
# Make Active Record use UTC-base instead of local time
# config.active_record.default_timezone = :utc
#config.gem "will_paginate", :source => "http://gems.rubyforge.org"
# Action Mailer configuration - from page 567-568 of the Agile Development book
# config.action_mailer.delivery_method = :smtp
#
config.action_mailer.smtp_settings = {
:address => "smtp.redacted.com",
:port => "25",
:domain => "redacted.com"
}
puts "setting smtp settings"
# See Rails::Configuration for more options
end
puts "outside config section ... before inflectors"
# Add new inflection rules using the following format
# (all these examples are active by default):
ActiveSupport::Inflector.inflections do |inflect|
# inflect.plural /^(ox)$/i, '\1en'
# inflect.singular /^(ox)en/i, '\1'
# inflect.irregular 'person', 'people'
# inflect.uncountable %w( fish sheep )
inflect.uncountable %w( sid fcc )
end
puts "after inflectors"
# Add new mime types for use in respond_to blocks:
# Mime::Type.register "text/richtext", :rtf
# Mime::Type.register "application/x-mobile", :mobile
# Include your application configuration below
require 'will_paginate'
puts "require will paginate"
# insert at top of ActiveRecord::Base.rb
# Indicates whether field names should be lowercased for legacy databse fields.
# If true, the field Product_Name will be +product_name+. If false, it will remain +Product_Name+.
# This is false, by default.
#cattr_accessor :downcase_legacy_field_names, :instance_writer => false
###downcase_legacy_field_names = false
# insert into column_methods_hash of ActiveRecord::Base.rb
# attr_final = downcase_legacy_field_names ? attr.to_s.downcase : attr
puts "here comes the monkey patch"
module ActiveRecord
class Base
# Indicates whether field names should be lowercased for legacy databse fields.
# If true, the field Product_Name will be +product_name+. If false, it will remain +Product_Name+.
# This is false, by default.
cattr_accessor :downcase_legacy_field_names, :instance_writer => false
##downcase_legacy_field_names = false
end
end
puts "monkey patch part 2"
# set all accessor methods to lowercase (underscore)
# add set_columns_to_lower to each model that needs it
class << ActiveRecord::Base
# Returns a hash of all the methods added to query each of the columns in the table with the name of the method as the key
# and true as the value. This makes it possible to do O(1) lookups in respond_to? to check if a given method for attribute
# is available.
def column_methods_hash #:nodoc:
#dynamic_methods_hash ||= column_names.inject(Hash.new(false)) do |methods, attr|
attr_final = downcase_legacy_field_names ? attr.to_s.downcase : attr
attr_name = attr_final
methods[attr_final.to_sym] = attr_name
methods["#{attr_final}=".to_sym] = attr_name
methods["#{attr_final}?".to_sym] = attr_name
methods["#{attr_final}_before_type_cast".to_sym] = attr_name
methods
end
end
# adapted from: http://wiki.rubyonrails.org/rails/pages/HowToUseLegacySchemas
def downcase_legacy_field_methods
column_names.each do |name|
next if name == primary_key
a = name.to_s.underscore
define_method(a.to_sym) do
read_attribute(name)
end
define_method("#{a}=".to_sym) do |value|
write_attribute(name, value)
end
define_method("#{a}?".to_sym) do
self.send("#{name}?".to_sym)
end
end
end
end
puts "monkey patch part 3"
ActiveRecord::Base.downcase_legacy_field_names = true
puts "monkey patch part 4"
module ActiveSupport
module Inflector
def textize(str)
str.to_s.gsub(/'/, '').downcase
#gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
#gsub(/([a-z\d])([A-Z])/,'\1_\2').
#tr("-", "_").
#downcase
end
end
end
puts "monkey patch part 5"
module ActiveSupport #:nodoc:
module CoreExtensions #:nodoc:
module String #:nodoc:
module Inflections
def textize
Inflector.textize(self)
end
end
end
end
end
###################################################################
### Code moved to the specific environment files.
### This way the schema gets reloaded on a deploy
###################################################################
## Establishes connections for the root classes of the various databases that
## must be connected to for SUI.
puts "load the database if we are in test mode"
if RAILS_ENV == "test" then
puts "if I see this and I'm not loading test, we have a problem"
Ird.load_database
end
puts "setting up the execption notifier"
ExceptionNotifier.exception_recipients = %w(me#redacted.com)
if RAILS_ENV == "Production"
ExceptionNotifier.sender_address = %("SUI Service" <service#redacted.com>)
ExceptionNotifier.email_prefix = "[SUI ERROR] "
else
ExceptionNotifier.sender_address = %("SUI #{RAILS_ENV.to_s.humanize} Service" <service#redacted.com>)
ExceptionNotifier.email_prefix = "[#{RAILS_ENV.to_s.humanize}: SUI ERROR] "
end
puts "local_ip function"
def local_ip
orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true
UDPSocket.open do |s|
s.connect '64.233.187.99', 1
s.addr.last
end
ensure
Socket.do_not_reverse_lookup = orig
end
puts "I am located at:#{local_ip}:"
puts "environment.rb is loaded"
If I set the rails gem to be used to version 2.1.2 everything loads and all the puts statements print as expected. When I change the gem version to 2.2.2 the last statement that I see printed is "setting smtp settings".
When I move the Rails::Initializer do |config| section to the bottom it fails in ways worse than where it is right now.
The ruby version that is loaded on the system is Ruby 1.8.6 patchlevel 111. It is running on RHEL5-64bit.
I'm stumped. Ideas? Suggestions?
Did you run rake rails:update?
Also, you might want to move most of the code into config/initializers/[anything].rb, allthough I hardly think that itself will solve your problems.

Resources