Include dynamic methods?

80 views
Skip to first unread message

Mike Funaro

unread,
Mar 19, 2015, 11:37:33 AM3/19/15
to ruby-...@googlegroups.com
I currently have a Grape API that contains 3 'sub APIs'. I am in the processing of modularizing some of the CRUD operations across the APIs. Some of the simple CRUD operations, like read for example, are identical across all three APIs. I was wondering if there is a way to dynamically create a method and then include it, so that I can include the method once and it can be used across all the APIs. 

Something like this...

module API
 
module Mixins
 
module CrudOperations
   extend
ActiveSupport::Concern

    included
do
     define_method
("get_#{self.class_name.downcase}") do |argument|
      model
= self.class.find(argument)
     
yield model
      model
     
end
   
end
 
end
 
end
end

Then include this module on my API resource files. I am a bit new to meta programming in ruby, so I am not sure that define_method would even work here but I am wondering more about the concept and looking for a nudge in the right direction, if there is one.

Thanks!




Daniel Doubrovkine

unread,
Mar 20, 2015, 6:54:05 AM3/20/15
to ruby-...@googlegroups.com
The `get` here is not a method that you need to define, it's a static method on the API class. So you can just do 

included do
    get do
    end
end

Check out ActiveSupport::Concern, too.




--
You received this message because you are subscribed to the Google Groups "Grape Framework Discussion" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ruby-grape+...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



--

Mike Funaro

unread,
Mar 20, 2015, 9:28:27 AM3/20/15
to ruby-...@googlegroups.com
Right, I am not trying to redefine (or just define) the get, put, post etc. I am trying to dynamically define a method that can fetch a record from the DB that would be used within a get for example. Since most all of my get methods look identical. 

So in a User endpoint I would have something like 

get do 
  user = get_user(permitted_params[:id]
  present user, with: UserEntity
end

However the method get_user (perhaps I should name it fetch_user to avoid confusion) would be dynamically defined when the module was included, so that this could then also be included in another API class as well. 
Sorry if I was unclear or still am being unclear. 

Daniel Doubrovkine

unread,
Mar 20, 2015, 9:35:24 AM3/20/15
to ruby-...@googlegroups.com
I see. All these methods are defined within inside_route, eg. present, https://github.com/intridea/grape/blob/cf4aac1afb57a77e3ceefa9df11a9f9fd47f2b47/lib/grape/dsl/inside_route.rb#L186, so add Grape::DSL::InsideRoute.extend <some module> and you should be all set.
Reply all
Reply to author
Forward
0 new messages