DISQUS

drawohara: [Ruby] temporary methods for dsls in ruby, aka - how to unextend

  • Michael Guterl · 1 year ago
    This is really interesting. Your ruby-fu never ceases to amaze me.

    Thanks for all that you contribute to the ruby community!
  • drawohara · 1 year ago
    i'm psyched to play with it -- been trying to figure how to do something like that for a long time! ;-)
  • s · 1 year ago
    you should write how your brain works!
    or simpler, how to become a better rubyist.
  • drawohara · 1 year ago
    it's quite simple really -- coffee and beer go in: code comes out. ;-)
  • Michael Guterl · 1 year ago
    in that case, next time i'm in boulder i'm buying you some beer! that is the least i owe you.
  • Pit Capitain · 1 year ago
    Nice code as always, Ara.

    Just two remarks:

    By using an instance variable in Methods.for it looks like you wanted to create the anonymous module only once, but you create a new one every time (actually two modules, but that's only a typo I suppose). If you want to create the module only once, you could change the code as follows:

    <pre>
    def Methods.new
    Module.new do
    def self.remove!
    instance_methods.each{|m| remove_method m}
    end
    end
    end

    def Methods.for object
    singleton_class_for(object) do
    unless defined? @dsl_methods
    @dsl_methods = Methods.new
    include @dsl_methods
    end
    @dsl_methods.module_eval(&Methods)
    @dsl_methods
    end
    end
    </pre>

    The second remark: you don't need instance_eval and the block parameter in the #dsl method, because you already call it in the scope of self. So all you need is a yield.

    Regards,
    Pit
  • Pit Capitain · 1 year ago
    Sorry for the indentation. Glad we aren't using Python :-)
  • drawohara · 1 year ago
    You can say that again!
  • drawohara · 1 year ago
    hey pit - nice to see you around here ;-)

    re

    1 - great fix. it also fixes an issue this code had - that of forever littering the singleton class with module methods.

    2 - yup. good call.

    i'm very happy with the approach thus far though - it's vastly simply than any approach i've found thus far for rapidly building intuitive and dsls.
  • Pit Capitain · 1 year ago
    Yes, the code is great. I especially liked your idea of using a lambda for (re)defining the methods in the helper module.
  • drawohara · 1 year ago