4 ms·
What do you find so fantastic? I'm starting to think I'm broken, because I just don't understand what's so amazing. I read Metaprogramming Ruby. It seems very
by MichaelGG 12y ago
What do you find so fantastic? I'm starting to think I'm broken, because I just don't understand what's so amazing.
I read Metaprogramming Ruby. It seems very excited to show you how you can do "myrow.columnname" instead of something like "myrow[" columnname"]. Likewise, I see people absolutely tickled that they can do "find_by_id(123)" without codegen vs "find_by("id", 123)". OK that saves a bit of syntax, but it's hardly breakthrough. And it's more elegantly solved with a specific dynamic lookup operator. It doesn't seem like it's worth the performance overhead or the pitfalls of a dynamic environment (thinking of the fun Rails had in the simple task of serializing HTTP bodies).
The only benefit I've found in Ruby that's not easily accessible in say, F#, is having reflection easily accessible. The .Net reflection libraries are clunkily designed. When you need it, being able to eval and such is handy. All the pieces are there, but they don't just expose an " eval" call or whatnot. But that's mainly a stdlib shortcoming, and wouldn't require giving up static analysis.
Do you have any pointers to examples where metaprogramming is really useful, to the point of paying the cost of Ruby?
- resca79 12y agoIf you are talking about ActiveRecord methods, `find_by_id(123)` or `find_by("id", 123)` are a little bit wrong both, you should use a simple `find(123)`
- venus 12y agofind_by_id/find_by aren't "wrong", they're just different. Sometimes you want to fall back to nil instead of raising an exception.
- asattarmd 12y agoclass Blog < ActiveRecord::Base end Ever wonder how that works? Metaprogramming. enum status: [ :active, :archived ]. validates :status, presence: true Ever wonder how that works? Metaprogramming. Used the awesome debugger, pry? Ever wonder how that works? Metaprogramming. `find_by_id` isn't the only thing that's implemented using Metaprogramming. Practically, everything within ActiveModel is achieved through Metaprogramming. It is one very important reason that allows Ruby to be so expressive.
- weaksauce 12y agoAlso, metaprogramming allows one to create find_by_id as a function at runtime after the first use of it, it becomes part of the class.
- MichaelGG 12y agoYou can expose the same functionality in, say, C# or F# if you want to give up static type checking. (Actually with F# type providers or a language with good macros, you can keep static analysis if you're willing to bind yourself to the database at build time.) This is just a use of dynamic binding. That's fine, I just thought there was more to it, something that requires a lack of static analysis, multi threading, etc.