{"id":1273,"date":"2010-02-05T14:11:27","date_gmt":"2010-02-05T13:11:27","guid":{"rendered":"http:\/\/www.devco.net\/?p=1273"},"modified":"2010-06-27T19:13:35","modified_gmt":"2010-06-27T18:13:35","slug":"adding_methods_to_a_ruby_class","status":"publish","type":"post","link":"https:\/\/www.devco.net\/archives\/2010\/02\/05\/adding_methods_to_a_ruby_class.php","title":{"rendered":"Adding methods to a ruby class"},"content":{"rendered":"
I’m just blogging this because it took me ages to figure out, it seems so simple now but I guess that’s how it usually goes.<\/p>\n
The problem I have is I want a plugin to be able to either make a method using the normal Ruby def foo<\/em> or via some DSL’ish helpers.<\/p>\n <\/code><\/p>\n The above code should make me two methods – do_something_action<\/em> and do_something_else_action<\/em> – they should be identical to viewers from the outside. Here’s the base class that makes this happen correctly:<\/p>\n <\/code><\/p>\n It’s pretty simple, we’re just using define_method in the scope of the module and that does the rest.<\/p>\n","protected":false},"excerpt":{"rendered":" I’m just blogging this because it took me ages to figure out, it seems so simple now but I guess that’s how it usually goes. The problem I have is I want a plugin to be able to either make a method using the normal Ruby def foo or via some DSL’ish helpers. class Foo […]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_et_pb_use_builder":"","_et_pb_old_content":"","footnotes":""},"categories":[1],"tags":[121,13],"_links":{"self":[{"href":"https:\/\/www.devco.net\/wp-json\/wp\/v2\/posts\/1273"}],"collection":[{"href":"https:\/\/www.devco.net\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.devco.net\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.devco.net\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.devco.net\/wp-json\/wp\/v2\/comments?post=1273"}],"version-history":[{"count":4,"href":"https:\/\/www.devco.net\/wp-json\/wp\/v2\/posts\/1273\/revisions"}],"predecessor-version":[{"id":1516,"href":"https:\/\/www.devco.net\/wp-json\/wp\/v2\/posts\/1273\/revisions\/1516"}],"wp:attachment":[{"href":"https:\/\/www.devco.net\/wp-json\/wp\/v2\/media?parent=1273"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.devco.net\/wp-json\/wp\/v2\/categories?post=1273"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.devco.net\/wp-json\/wp\/v2\/tags?post=1273"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}<\/p>\n
\r\nclass Foo
<\/p>\n
\r\nclass Base\r\n def self.register_input(input, &block)\r\n name = input[:name]\r\n\r\n self.module_eval { define_method(\"#{name}_action\", &block) } if block_given?\r\n end\r\nend\r\n<\/pre>\n