This presentation covers about the core concepts of ruby dynamic nature of programming that acts as the foundation for building frameworks, gems etc. This is mainly for people who are working with Ruby on Rails, as this can be used in creating code on the fly and using 'DRY' nature a lot while coding.
9. Blocks
- {} or do-end
- block object can be created (lambda, proc,
¶m)
- all are of same object proc object.
10. Lambda & Proc
- Both are proc objects.
- params passed to them.
- return
11. Bindings
- Captures the current state, and returns as an
binding object.
- This can be achieved using method “binding”.
- Used with “eval” method by passing as an
option.
12. define_method
- Used to create methods on the fly
(dynamically).
- Dry up code.
ex: find_by_*, attr_accessors etc ….
13. code-sample.
Usual code:
def user; @data[:user]; end
def email; @data[:email] end
def food; @data[:food]; end
Using define_method:
%w(user email food).each do |meth|
define_method(meth) { @data[meth.to_sym] }
end
14. Few Other Hook Methods.
- class_eval
- instance_eval
- instance_variable_(get,set)
15. class_eval & instance_eval
- These methods are used for defining class
and instance methods for a class on the
runtime.
- class_eval is used for defining instance
methods
- instance_eval is used for creating the class
methods.
16. Sample Code.
class_eval
class Person
end
Person.class_eval do
def say_hello
"Hello!"
end
end
jimmy = Person.new
jimmy.say_hello # "Hello!"
instance_eval
class Person
end
Person.instance_eval do
def human?
true
end
end
Person.human? # true