background preloader

Meta programming

Facebook Twitter

Reflection - How do I get a message sender in SmallTalk (Pharo) I'm confused with block in ruby, compared to smalltalk. 10 things you should know about method_missing | thirdbIT. [update, 9:27 a.m., 8/1/2007: welcome, reddit readers. annoyed at me for calling this post "10 things"? Well, then you'll really hate me after reading this post!] 1. method_missing is a Ruby kernel method and everyone should know about it. 2.

Rails implements some of its funkiest magic with method_missing. When you ask your model to find_by_freaky_column_name, and it does so, that’s because ActiveRecord::Base overrides the kernel’s method_missing method. 3. method_missing is the method of last resort. 4. 5. 6. Irb(main):227:0> "thingy".invoke_method_missing_for_demo_purposes("arg", "other arg") NoMethodError: undefined method `invoke_method_missing_for_demo_purposes' for "thingy":String from (irb):227 7. 8. method_missing is said to be slower than calling an actually-already existing method, unsurprisingly, given that it’s by definition invoked only after Ruby’s looked everywhere else for your method. 10.

Don’t trust that _why and all his chunky bacon? Popularity: 58% [?] Ruby: instance_eval and class_eval method definitions. In yesterday's entry on Cleaning up Controller Tests you can find the following code. # example 1...test_class.class_eval do define_method :setup do ... endendtest_class.class_eval &block... An earlier version of this code only used one call to the class_eval method. # example 2...test_class.class_eval do define_method :setup do ... end instance_eval &blockend... Example 2 works when your controller tests contain only test methods. # example 3controller_tests do test "should add the params" do assert_equal 4, Math.add(2,2) end test "should multiply the params" do assert_equal 9, Math.multiply(3,3) endend However, Example 2 stops working if your test class contains any helper methods. # example 4controller_tests do test "should not save if first name is nil" do person = valid_person person.first_name = nil assert_equal false, person.save end def valid_person Person.new(...) endend So, what's the difference between example 1 and example 2?

How does define_method fit into this picture? The Ruby Object Model and Metaprogramming. Want to receive a weekly email containing the scoop on our new titles along with the occasional special offer? Just click the button. (You can always unsubscribe later by editing your account information). Give us an email and a password (you can use the password later to log in and change your preferences). We'll send you a newsletter roughly once a week. Metaprogramming lets you program more expressively. This makes your code easier to write and easier to maintain and extend.

Buy Now Download and watch DRM-free episodes when and where it's convenient for you You get Theora Ogg, iPod/iPhone 3, iPad/iPhone 4, and QuickTime formats. All the episodes in this series have been released. About this Screencast Initially, metaprogramming Ruby can seem really difficult. Well, the good news is that it really isn’t that complex. It doesn’t matter if you’ve been programming Ruby for a month or for five years.

Dave talks about the series in this free preview Contents and Extracts Audience. Ruby Metaprogramming. Sunday, April 17, 2005 Seeing Metaclasses Clearly If you're new to metaprogramming in Ruby and you'd like to start using it, perhaps these four methods could give you a bit more vision. class Object def metaclass; class << self; self; end; end def meta_eval &blk; metaclass.instance_eval &blk; end def meta_def name, &blk meta_eval { define_method name, &blk } end def class_def name, &blk class_eval { define_method name, &blk } end end I've been keeping these methods in a file called metaid.rb and it's a start toward building a little library that can simplify use of metaclasses.

About Classes Well, what is a Class? >> class MailTruck >> attr_accessor :driver, :route >> def initialize( driver, route ) >> @driver, @route = driver, route >> end >> end >> m = MailTruck.new( "Harold", ['12 Corrigan Way', '23 Antler Ave'] ) => @driver="Harold"> >> m.class => MailTruck An Object is storage for variables.

Classes Are Objects Look! .c( whytheluckystiff )o. -- Seeing Metaclasses Clearly. If you’re new to metaprogramming in Ruby and you’d like to start using it, perhaps these four methods could give you a bit more vision. class Object # The hidden singleton lurks behind everyone def metaclass; class << self; self; end; end def meta_eval &blk; metaclass.instance_eval &blk; end # Adds methods to a metaclass def meta_def name, &blk meta_eval { define_method name, &blk } end # Defines an instance method within a class def class_def name, &blk class_eval { define_method name, &blk } end end I’ve been keeping these methods in a file called metaid.rb and it’s a start toward building a little library that can simplify use of metaclasses.

Let’s talk about metaclasses and I advise you to keep metaid.rb at your side. Take time to run some code from this article and you’ll understand much better. About Classes Well, what is a Class ? An Object is storage for variables. >> m.instance_variable_set( "@speed", 45 ) => 45 >> m.driver => "Harold" These methods are stored in the class.

Look! Ruby Class Methods vs. Methods in Eigenclasses. Reflection, ObjectSpace, and Distributed Ruby @ Programming Ruby. Understanding Ruby Blocks, Procs and Lambdas - Robert Sosinski. Do You Understand Ruby’s Objects, Messages and Blocks? Do You Understand Ruby’s Objects, Messages and Blocks? This guest post is by Ed Howland, an independent consultant who has worked in Ruby and RoR for more than 5 years, since the 0.13 days of Rails. He has over 22 years in the software development industry working on mainly O-O projects in C/C++, Java, Perl and PHP. Ed is a frequent speaker at regional conferences and local Ruby/Linux user groups. Introduction Ruby is a very elegant and expressive language. Consider the following complete Ruby program (one of the first examples I was exposed to, reconstructed from memory): #! Running . But how does it work? Actually, all that is going on here is a bunch of Ruby objects that are talking to each other. Objects In Ruby, nearly everything is an object.

Messages :message [payload1, ... payloadN] A Ruby message consists of a name, usually represented by a symbol such as :message, and an optional payload. When the object receives the message, it handles it and returns some other object. Blocks Methods. Three implicit contexts in Ruby - 世界線航跡蔵. Yehuda Katz wrote an article about self and metaclass. In the article he said that Person.instance_eval assigns Person's metaclass to self for a class Person.

But this is obviously wrong. class Person; end Person.instance_eval{ p self } class Person; end Person.instance_eval{ p self } #=> Person As I mentioned in an old article, though I'm sorry about it is written in Japanese, Ruby always has three implicit contexts: self), so called `klass' and the constant definition point. Self self is the self which you know. P self class Foo def bar(a = (p self)) end end foo = Foo.new foo.bar class Foo class Baz < (p self; self) end end p self # displays "main" class Foo def bar(a = (p self)) end end foo = Foo.new foo.bar # displays "#<Foo:0x471004>" class Foo class Baz < (p self; self) # displays "Foo" end end On the top level, a special instance of Object named "main" is the self. If you invoke a method without giving an explicit receiver, self will receive the invocation. so called `klass' Examples.

What exactly is metaprogramming. Ruby Matters: Meta-programming, Synthesis, and Generation. In my last Ruby Matters blog post, I talked about meta-programming in Ruby, contending that Ruby gives you "places to put your stuff". I always wondered about meta-programming in Smalltalk and how that compares to Ruby, and Where to Put Stuff in Smalltalk.

The final piece of the puzzle came after I talked to Glenn Vanderburg (the Chief Scientist of Relevance). I was puzzled as to why the Gang of Four book (which had examples in both C++ and Smalltalk) didn't have more meta-programming. Lots of the design patterns are almost trivially easy to implement with meta-programming, but they didn't do that in the Smalltalk examples. They used the same structural approach as C++. It looks more and more to me that the Design Patterns book was really just a way to solve problems in C++ that should have been easier to solve in a more powerful language like Smalltalk. Which is why I was puzzled about the lack of of more meta-programming solutions in Smalltalk. Next up, "design patterns" in Ruby. Metaprogramming Ruby: class_eval and instance_eval | Jimmy Cuadra.

I am currently reading a great book called Metaprogramming Ruby, an in-depth guide to dynamic code and code generation in Ruby. There have been a lot of light bulb moments for me while reading. Sometimes when the book explains a concept or Ruby feature, it sheds light on things I've seen in other people's code – things I've always wondered about.

One such example is class_eval and instance_eval. These methods allow you to evaluate arbitrary code in the context of a particular class or object. They're slightly similar to call, apply and bind in JavaScript, in that you are altering the value of self (this in JavaScript) when you use them. Let's take a look at some examples to demonstrate their usage. class Personend Person.class_eval do def say_hello "Hello! " In this example, class_eval allows us to define a method within the Person class outside of its original definition and without reopening the class with the standard syntax. Class Personend Person.instance_eval do def human? Metaprogramming in Ruby: It’s All About the Self. November 15th, 2009 After writing my last post on Rails plugin idioms, I realized that Ruby metaprogramming, at its core, is actually quite simple.

It comes down to the fact that all Ruby code is executed code–there is no separate compile or runtime phase. In Ruby, every line of code is executed against a particular self. Consider the following five snippets: All five of these snippets define a Person.species that returns Homo Sapien. Now consider another set of snippets: These snippets all define a method called name on the Person class. First, it is important to understand how Ruby’s metaclass works. Person is an instance of Class, so any methods added to Class are available on Person as well. What’s going on here is that we’re adding the speak method to matz‘s metaclass, and the matz object inherits from its metaclass and then Object.

In fact, matz‘s “class” is its invisible metaclass. Here, we are adding the name method to the Person class. Here, we combine several of the techniques. Ruby Matters: A Place to Put Your Stuff. Why are so many people into Ruby? I get this question a lot because I speak at a lot of Java conferences and talk about Ruby and JRuby. In this and several more blog entries, I'm going to explore this question in depth. For myself and many of my peers, it was a rite of passage to learn all the intricate tricky stuff in C++. Once I got over my fascination with C++ and got tired of banging my head against all of the arcane nonsense in the language (I used to know the details of all the different ways you could use the word const, but I've fortunately purged that knowledge), I asked one of my colleagues why he continued to love it so much.

"Knowing C++ makes me part of the C++ priesthood. When people ask me questions, I'm purposely cagey when I give them answers because I think they should work as hard as I did to figure this stuff out. I don't want to give my advantage away. " After a brief visit to the refugee camp of Delphi, I made it to Java and thought I was in heaven. What Are Metaclasses? - { |one, step, back| } I seemed to have accidently started a twitter storm debate on metaclasses in Ruby.

Somethings are just are to say in 140 characters. So here’s my take on the issue. Singleton Class / Eigenclass / Metaclass … What? Ruby has this concept of per-class methods. In other words, you can define a method on an object, rather than on its class. Such per-object methods are callable on that object only, and not any other object in the same class. Implementation wise, these per-object methods are defined in an almost invisible class-like object called the “Singleton Class”.

Some people object to the name “singleton class”, complaining that it is easily confused with the singleton pattern from the Gang of Four book. I objected to the use of the name “metaclass” for the singleton class on the grounds that metaclass has a well understood meaning in non-Ruby circles, and that the singleton class is not a metaclass. So, What’s a Metaclass?

According to wikipedia: So Singleton classes aren’t Metaclasses?