josh
josh

Reputation: 10318

How do I add a custom method to a Ruby library?

I'm using the Restforce library to do some Salesforce queries. To do the queries, I usually do the following:

client = Restforce.new :username => 'user', :password => 'pass', :security_token => 'token', :client_id => 'client_id', :client_secret => 'client_secret'

And then call client.query to query Salesforce.

I want to create a custom method called query_with_alises so that I can call client.query_with_aliases to do some custom functionality.

How would I do this without editing the source code of the library itself?

Upvotes: 0

Views: 95

Answers (2)

Doodad
Doodad

Reputation: 1518

You can just open the class again and add any method you want.

Though the exact meaning is matter of debate, this is called monkey-patching. Some consider monkey-patching only overriding/redefining existing methods (which can be kinda dangerous), other consider any kind of opening existing classes and adding anything, even if they are new methods.

In your specific case, you can monkey-patch Client class from Restforce like that:

class Restforce::Data::Client
  def query_with_aliases

    # PUT YOUR CODE HERE

  end    
end

Every other method inside Client will keep existing and functioning and you will only add the query_with_aliases.

Upvotes: 1

Vasfed
Vasfed

Reputation: 18454

Monkey-patch some methods - in ruby you can open class again and add some methods, or use some technique like

module MyPatches
  def query_with_aliases
    # code here...
  end
end

TargetClass.send :include, MyPatches

Upvotes: 1

Related Questions