Search code examples
rubycommand-line-interfacethor

How to set a method dynamically as other class method


Im new to Ruby, and im creating a cli app with Thor and some additional gems. My problem is that i take user input (from the console) and pass the data as a variable to a existing method (This method is from a gem)

My method

def search(searchtype, searchterm)

  search = OtherClass.new  
  result = search.search.searchtype keyword: "#{searchterm}"
  puts result
  # search.search.searchtype is not a method in the gem im using.

end

The OtherClass gem has these search methods: users, repos

The users method

def users(*args)

  arguments(args, :required => [:keyword])
  get_request("/legacy/user/search/#{escape_uri(keyword)}", arguments.params)

end

The repos method

def repos(*args)
  arguments(args, :required => [:keyword])

  get_request("/legacy/repos/search/#{escape_uri(keyword)}", arguments.params)
end

So how can i pass in the user data to the method from the OtherClass? Heres something like what i would want to do. The SEARCHTERM would be dynamically passed to the search.search object as a method parameter.

def search(SEARCHTYPE, searchterm)

 search = OtherClass.new  
 result = search.search.SEARCHTYPE keyword: "#{searchterm}"
 puts result

end

The "#{searchterm}" works as expected, but i also want to pass in the method to the search.search object dynamically, this could probably be done with if's but im sure theres a better way, maybe the Ruby way to solve this problem.

Finally i would want to be able to use this little program like this (the serch method)

./search.rb search opensource linux

(where opensource could be users, or another type of search, and linux could be the search keyword for the searchtype)

If this is possible i would apprechiate any help!

Thnx!


Solution

  • If you'd like to call a method dynamically, use Object#send.

    http://ruby-doc.org/core-1.9.3/Object.html#method-i-send

    I would caution against sending a method that was obtained by user input though, for security reasons.