Search code examples
ruby-on-railsrubygemscustomizing

Customizing/Overriding Rails SimpleForm Gem


I'm using the Rails gem SimpleForm, but I think my question may be applicable to any gem.

https://github.com/plataformatec/simple_form

It has a lot of great features and customization, but I'm looking to go a bit further. For example, I really wish the markup generated had no default classes inserted into it, but I'd still like the ability to insert my own manually. I found that I could remove some of the classes by commenting out lines in the gem files. However this is outside of my project-- I would want a DRY solution that will stay with my project when I deploy to production, preferably without having to pack all of my gems.

I imagine this is a common situation that could apply to any gem, and I should be able to override any gem wholly or partially probably by adding customs files in my project that override the gem... but I'm not sure how.

Any help would be appreciated! Thanks.


Solution

  • Are you talking about monkey patching? Say your gem has a class in a file

    # simple_form_gem/lib/some_file.rb
    class A
      def some_method
        puts 'A'
      end
    end
    

    If you want to change the output of #some_method then you can create an initializer file and do

    # config/initializers/my_monkey_patch_for_simple_form_gem.rb
    class A
      def some_method
        puts 'duck punching'
      end
    end
    

    Your monkey patch will only affect A#some_method, and not other methods in A. Just make sure the output of your monkey patch won't break something else in the gem.