On 2011-02-04 20:03, spir wrote:
On 02/04/2011 04:33 PM, Jacob Carlborg wrote:

I recommend looking at Ruby, it has very good support for runtime
reflection.
ActiveRecord in Rails is hevaly based on runtime reflection. For
example, given
the following Ruby class:

class Post < ActiveRecord::Base
end

The class "Post" maps to the database table "posts", no configuration is
necessary. Then you can use the column names in the table as fields to
set and
get data, like this:

post = Post.new
post.title = "some title"
post.body = "the body"
post.save # will update the database

All this is done using runtime reflection. Then you can query the
database,
also using runtime reflection:

Post.find_by_name_and_body("some title", "the body")

Will find the first row where "title" and "body" matches the given
values.

FWIW, python example of "Calling method by name" (using no exotic feature):

class C:
def __init__(self, x):
self.x = x
def write (self, thing):
print "%s == %s ? %s" \
%(self.x,thing, self.x==thing)

def runMethodWithArgs (object, name, *args):
method = getattr(object, name)
method(*args)

c= C(1.11)
runMethodWithArgs(c, "write", 2.22)
# --> 1.11 == 2.22 ? False

(Explanations if needed.)

Denis

Actually I never showed how to do "call by name" in Ruby, just how it can be used. Ruby has "built in" (not in the language but in the Object class) support for this:

p Object.new.send(:to_s) # :to_s is a symbol, basically an immutable lightweight string

The above will print something like: "#<Object:0x101279bb8>"

To implement the "find_by" methods used in my previous examples you implement the "method_missing" method:

class Foo
    def method_missing (method, *args, &block)
        p method, args
    end
end

Foo.new.bar 3, 4

Will print:

:bar
[3, 4]

--
/Jacob Carlborg

Reply via email to