简体   繁体   中英

Monkey (maybe?) Patching a Gem In My Rails Apps

I'm 100% sure of the terminology, still relatively new to the rails world, so forgive that if I'm too far off with the monkey patch, that might not apply in this case.

I am using a gem, LongURL, that lengthens shortened urls. By default the gem uses longurl.org, but we push a few hundred thousand urls through it a day and figured it'd be nicer for everyone to bring that service internally. I just need to change 2 constants to point to my own url.

module LongURL
  ShortURLMatchRegexp = /http:\/\/[\/\-_.a-z0-9]+/im

  # Urls for longurl
  EndPoint        = URI.parse("http://api.longurl.org/v1/expand")
  ServiceEndPoint = URI.parse("http://api.longurl.org/v1/services")
end

It doesn't seem like such a minor change is worthy of a fork, what are some good, rails idiomatic?, approaches to making minor changes like this?

Thanks

When you're redefining constants you'll need to remove the old ones first, then re-apply the new ones. Your patch might look like this:

module LongURL
  remove_const(:ShortURLMatchRegexp)
  ShortURLMatchRegexp = /http:\/\/[\/\-_.a-z0-9]+/im

  # ... (etc) ...
end

This should help avoid warnings about redefining an existing const.

As far as making it Railsy, put that into config/initializers and make sure it's clearly labelled, perhaps longurl_monkeypatch.rb so there's no confusion as to what kind of hackery is going on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM