ruby programming language(ch8)
Ch8
type,class,module
ancestry
|
|
def
|
|
eval
binding & eval
eval 1 [2]:
- eval string
- Binding object
|
|
instance_eval & clas_eval
- code evaluated in correspond context (to instance or class object)
- both can accept block instead of string
reflect var
<instance>.instance_variables<class>.class_variablesclass.constantsquery:
eval(".. #{..} ..")- attr:
o.instance_variable_set(:@x, 0)o.instance_variable_get(:@x), similarclass_xxxconst_xxx - test:
_defined?_missing?
method
.methods==.public_methods.protected_methods.private_methods<class>.instance_methodsalternative prefix:publicprotectedprivate.singleton_methods- trivial for instance
- class methods for class
methodsgives list, with(false)to exclude inheritedmethod(:sym)to get method object<method>.call ..<object>.send(:sym, ..)
define
instance:
|
|
class:
|
|
or
|
|
eigenclass gets the class object, recall a specified class is a instance
hook
when:
- classes are subclassed
- modules are included
- methods are defined
- ..
ed method |
when | param | extra |
|---|---|---|---|
inherited |
new class defined | new class object | inherited by subclass |
included |
module included | class or module object included in | |
extended |
object extended | .. | |
method_added |
instance method | :”new method name” | |
singleton_.. |
singleton/class method | :”singleton_method” | self invoked when define |
others:
removed/undefinedsingleton_removed/_undefined
tracing
__FILE____LINE__SCRIPT_LINES__: hash { filename: array of lines of source file } filled whenrequireandload- include main file:
SCRIPT_LINES__ = {__FILE__ => File.readlines(__FILE__)} - refer line of code:
SCRIPT_LINES__[__FILE__][__LINE__-1]
- include main file:
trace_var(:var): when changed
ObjectSpace
.each_object.id2refinverse to.object_id- ..
def method dynamically
class_eval
directly interpolate identifiers into method body
|
|
define_method
rely on reflective methods
|
|
DSL
A DSL is just an extension of Ruby syntax (with methods that look like keywords)
or API that allows to solve problem or represent data more naturally.
XML as example utilized ruby’s:
- block
- parentheses-optinal invoke
- passing hash literals without curly braces
method_missing
|
|
usage example:
|
|