How to convert a ruby hash object to JSON?

One of the numerous niceties of Ruby is the possibility to extend existing classes with your own methods. That’s called “class reopening” or monkey-patching (the meaning of the latter can vary, though). So, take a look here: car = {:make => “bmw”, :year => “2003”} # => {:make=>”bmw”, :year=>”2003″} car.to_json # NoMethodError: undefined method `to_json’ … Read more

Rails I18n validation deprecation warning

Important: Make sure your app is not using I18n 0.6.8, it has a bug that prevents the configuration to be set correctly. Short answer In order to silence the warning edit the application.rb file and include the following line inside the Rails::Application body config.i18n.enforce_available_locales = true The possible values are: false: if you want to … Read more

Ruby: Calling class method from instance

Rather than referring to the literal name of the class, inside an instance method you can just call self.class.whatever. class Foo def self.some_class_method puts self end def some_instance_method self.class.some_class_method end end print “Class method: ” Foo.some_class_method print “Instance method: ” Foo.new.some_instance_method Outputs: Class method: Foo Instance method: Foo

String concatenation in Ruby

You can do that in several ways: As you shown with << but that is not the usual way With string interpolation source = “#{ROOT_DIR}/#{project}/App.config” with + source = “#{ROOT_DIR}/” + project + “/App.config” The second method seems to be more efficient in term of memory/speed from what I’ve seen (not measured though). All three … Read more

Uninstall old versions of Ruby gems

# remove all old versions of the gem gem cleanup rjb # choose which ones you want to remove gem uninstall rjb # remove version 1.1.9 only gem uninstall rjb –version 1.1.9 # remove all versions less than 1.3.4 gem uninstall rjb –version ‘<1.3.4’

Rails update_attributes without save?

I believe what you are looking for is assign_attributes. It’s basically the same as update_attributes but it doesn’t save the record: class User < ActiveRecord::Base attr_accessible :name attr_accessible :name, :is_admin, :as => :admin end user = User.new user.assign_attributes({ :name => ‘Josh’, :is_admin => true }) # Raises an ActiveModel::MassAssignmentSecurity::Error user.assign_attributes({ :name => ‘Bob’}) user.name # … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)