Pages

Monday, June 1, 2015

Check if ActiveRecord object is valid with params before updating to Database

To update the attributes without saving them, you can use
@obj.assign_attributes( params[:obj] )
Then to check if the object is valid, you can call
@obj.valid?
If the object is not valid, you can see the errors (only after calling .valid?) by calling
@obj.errors
If the object is valid, you can save it by calling
@obj.save
However, all of this usually isn't necessary. If the object isn't valid, then ActiveRecord won't save the object to the database, so all of the attribute changes are forgotten when you leave the controller action.
Also, since an invalid record won't be saved to the database, you can always just call Object.find() again to get the original object back.

Wednesday, March 18, 2015

Adding Layouts to Devise Views

Add following code to your Devise.rb file

# append to end of config/initializers/devise.rb
Rails.application.config.to_prepare do
  Devise::SessionsController.layout "devise"
  Devise::RegistrationsController.layout proc { |controller| user_signed_in? ? "application" : "devise" }
  Devise::ConfirmationsController.layout "devise"
  Devise::UnlocksController.layout "devise"
  Devise::PasswordsController.layout "devise"
end

Thursday, March 12, 2015

Access WEBrick from a different PC

By using the below command, One can access webrick from different PC

rails s -b IP_ADDRESS -p PORT

Wednesday, January 14, 2015

Fetch a Average Color from an Image

One can fetch a average color from an image using Rmagick with the below snippet.

img =  Magick::Image.read("http://SOME_IMAGE_URL").first
pix = img.scale(1, 1)
avg_color_hex = pix.to_color(pix.pixel_color(0,0)
It will return the Color code(The maximum color used in that image).