Create class names from strings
"foo_and_bars".classify # => "FooAndBar" #String
"foo_and_bars".classify.constantize # => "FooAndBar" #Class
# in case of singular names
"business".classify # => "Busines"
"business".camelize # => "Business"
"business".camelize.constantize #=> "Business" #Class
Related cards:
Class_eval and Instance_eval
class_eval is called on a class object and is used to create instance methods for the class at runtime.
%w(administrator developer teamlead tester).each do |user|
class_eval <<-EOR
def is_#{user}?
site == "MYACCOUNT_#{org.upcase}" ...
listing methods of class and object (instance)
class Myclass
def one
puts "one is called"
end
end
ss = Myclass.new
puts Myclass.methods
# returns array of methods for the class. Includes both class and instance methods and methods inherited from parents.
puts Myclass.instanc...
Abstract classes in rails
class AbstractModel < ActiveRecord::Base
self.abstract_class = true
end
class Foo < AbstractModel
end
class Bar < AbstractModel
end
Foo and Bar both inherit properties and methods of the Abstract Model while being in separate tables...
Clearing out old Rails session records from a MySQL database
To delete sessions based on a hard coded cut-off date:
DELETE FROM sessions WHERE updated_at < STR_TO_DATE('23.05.2013',GET_FORMAT(DATE,'EUR'));
Replacing cut-off date with period of inactivity
DELETE FROM sessions WHERE updated_at ...
Change a string into class name
In Ruby, class names are constants, so you can do
str = "Thing" #=> "Thing"
Kernel.const_get(str) #=> Thing
Find Class of a variable in Javascript
As we have object.class method in Ruby, to check the class of a variable in Javascript, here is the snippet
var ss = "some string";
alert (typeof ss); #=> string
alert (typeof pp); #=> undefined
include and extend in ruby
The extend method will mix a module’s methods at the class level.
On the other hand, the include method will mix a module’s methods at the instance level, meaning the methods will become instance methods of the class.
module Stringify
# R...
difference between attr_accessor and initialize
attr_accessor is used to create setter and getter methods for instance variables so that they can be accessed outside the class. initialize is the special method in ruby that gets called when an object is instantiated.
class Birthday
attr_ac...
Using send method in Ruby
In Ruby, send is often introduced as a way to show how everything is an object
1.send(:+, 1) ## -> 2
It can also be used to call private or protected methods from outside a given class as explained below.
class Myclass
def method...
add sublime text option to the contextual menu
After installing sublime text, we must be able to open text files with it. Right click on a text file and you must see the option "open with sublime text". In case you don't , click Open with other applications and you should see Sublime text opti...