I'm getting started with Ruby and Rails 3. There is a Rails Engine (packaged as a Gem) that I would like to use but it doesn't work exactly as I would like it to. I want to make some slight modifications but don't want to have to create my own forked version. I think this is where monkey patching becomes useful.
Being new to Ruby (and coming from a PHP background) monk开发者_JAVA技巧ey patching is a new concept to me. How would I go about monkey patching an existing gem, and how would I go about organizing my modifications? I'm looking for some "best practice" approaches to this.
This is a very broad question because you didn't mention what gem or how you wanted to modify the behavior, but...
In general, the way to approach this (one way to approach this) is open the gem up. Use an editor that can open all the files so you can easily flip from one to another. When looking at the gem, figure out which class contains the functionality you want to change.
So, you go to your test or spec directory and write a test like:
# Write tests to your API the way you want to write
# your code, not how you expect you *will* write that
# code.
def test_it_spits_out_my_awesome_error_message
# some setup code
assert_equal my_obj.spit_out_error_message, "some expected error message"
end
and run your tests. Of course they fail because your new functionality is not in place.
Now, say your change goes in spit_out_error_message
in class AwesomeAuthentication
. You can create a class in your project -- probably in lib/awesome_auth.rb or something like that. In it, you do as described here: Rails 3: alias_method_chain still used?. You'll also want to read this: http://yehudakatz.com/2009/03/06/alias_method_chain-in-models/, as it describes modifying an existing class using this technique (scroll to the bottom).
So you create a new spit_out_error_message
, cobble it in as described above and rerun the tests.
精彩评论