Coder Social home page Coder Social logo

prependers's Introduction

Prependers

CircleCI

Prependers are a way to easily and cleanly extend third-party code via Module#prepend.

Installation

Add this line to your application's Gemfile:

gem 'prependers'

And then execute:

$ bundle

Or install it yourself as:

$ gem install prependers

Usage

To define a prepender manually, simply include the Prependers::Prepender[] module. For instance, if you have installed an animals gem and you want to extend the Animals::Dog class, you can define a module like the following:

module Animals::Dog::AddBarking
  include Prependers::Prepender[]

  def bark
    puts 'Woof!'
  end
end

Animals::Dog.new.bark # => 'Woof!'

Extending class methods

If you want to extend a module's class methods, you can define a ClassMethods module in your prepender:

module Animals::Dog::AddFamily
  include Prependers::Prepender[]

  module ClassMethods
    def family
      puts 'Canids'
    end
  end
end

Animals::Dog.family # => 'Canids'

As you can see, the ClassMethods module has automagically been prepended to Animals::Dog's singleton class.

Using a namespace

It can be useful to have a prefix namespace for your prependers. That way, you don't have to worry about accidentally overriding any vendor modules. This is actually the recommended way to define your prependers.

You can accomplish this by passing the :namespace option when including Prependers::Prepender:

module MyApp
  module Animals
    module Dog
      module AddBarking
        include Prependers::Prepender[namespace: MyApp]

        def bark
          puts 'Woof!'
        end
      end
    end
  end
end

Verifying original sources

One issue you may run into when extending third-party code is that, when the original implementation is updated, it's not always obvious whether you have to update any of your extensions.

Prependers make this a bit easier with the concept of original source verification: you can compute a SHA1 hash of the original implementation, store it along with your prepender, and then verify it against the current hash when your application loads. If the original source changes, you get an error asking you to ensure your prepender is still relevant.

To use original source verification in your prependers, pass the :verify option:

module Animals::Dog::AddBarking
  include Prependers::Prepender[verify: nil]

  # ...
end

When you load your application now, you will get an error with instructions on how to set the proper hash:

Prependers::OutdatedPrependerError:
  You have not defined an original hash for Animals::Dog in Animals::Dog::AddBarking.

  You can define the hash by updating your include statement as follows:

      include Prependers::Prepender[verify: 'f7175533215c39f3f3328aa5829ac6b1bb168218']

At this point, you should update your prepender with the correct hash:

module Animals::Dog::AddBarking
  include Prependers::Prepender[verify: 'f7175533215c39f3f3328aa5829ac6b1bb168218']

  # ...
end

Now, when the underlying implementation of Animals::Dog changes because of a dependency update or other reasons, Prependers will raise an error such as the following:

Prependers::OutdatedPrependerError:
  The stored hash for Animals::Dog in Animals::Dog::AddBarking is
  f7175533215c39f3f3328aa5829ac6b1bb168218, but the current hash is
  2f05682e4f46b509c23a8418d9427a9eeaa8a79e instead.

  This most likely means that the original source has changed.

  Check that your prepender is still valid, then update the stored hash:

      include Prependers::Prepender[verify: '2f05682e4f46b509c23a8418d9427a9eeaa8a79e']

Original source verification also works when a module is defined in multiple locations.

NOTE: Due to limitations in Ruby's API, it is not possible to use source verification with modules that don't define any methods. Prependers will raise an error if you try to do this.

Autoloading prependers

If you don't want to include Prependers::Prepender[], you can also autoload prependers from a path, they will be loaded in alphabetical order.

Here's the previous example, but with autoloading:

# app/prependers/animals/dog/add_barking.rb
module Animals::Dog::AddBarking
  def bark
    puts 'Woof!'
  end
end

# somewhere in your initialization code
Prependers.load_paths(File.expand_path('app/prependers'))

Note that, in order for autoprepending to work, the paths of your prependers must match the names of the prependers you defined.

You can pass multiple arguments to #load_paths, which is useful if you have subdirectories in app/prependers:

Prependers.load_paths(
  File.expand_path('app/prependers/controllers'),
  File.expand_path('app/prependers/models'),
  # ...
)

You can pass the :namespace option to #load_paths to have it forwarded to all prependers:

Prependers.load_paths(
  File.expand_path('app/prependers/controllers'),
  File.expand_path('app/prependers/models'),
  namespace: Acme,
)

Integrating with Rails

To use prependers in your Rails app, simply create them under app/prependers/models, app/prependers/controllers etc. and add the following to your config/application.rb:

Prependers.setup_for_rails

#setup_for_rails accepts the same options as #load_paths.

Development

After checking out the repo, run bin/setup to install dependencies. Then, run rake spec to run the tests. You can also run bin/console for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run bundle exec rake install. To release a new version, update the version number in version.rb, and then run bundle exec rake release, which will create a git tag for the version, push git commits and tags, and push the .gem file to rubygems.org.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/nebulab/prependers.

License

The gem is available as open source under the terms of the MIT License.

prependers's People

Contributors

aldesantis avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

prependers's Issues

Add a simple way to extend class methods

Right now you need to define self.prepended method and use the class passed as a parameter to override all class methods. It would be great to automatically use all methods defined in a nested module called ClassMethods to override class ones:

module Animals::Dog::AddGenus
  module ClassMethods
    def genus
      'canis'
    end
  end
end

Animals::Dog.genus #=> 'canis'

Check for integrity of the original files

A while ago, we discussed the possibility of adding something such as Deface's :original option, which would basically be a SHA1 of the file that is being modified at the time the override is written. The SHA1 is then compared with the current SHA1 of the original file every time, so that the developer knows if the original file has changed (e.g. because of a dependency update) and can adjust the override accordingly.

It would be very cool to adopt a similar pattern in Prependers, however there are a couple of challenges:

  • Ruby modules can be defined and re-defined in multiple places at once. We'd have to somehow find all the sources for a module and combine their contents into a single SHA1.
  • There may be multiple Ruby modules defined in the same file.
  • Ruby files often contain a lot of boilerplate (e.g. comments, whitespace, syntax artifacts) that doesn't affect the behavior or interface of the code itself.

Ideally, we find a library that allows us to easily compute the SHA1 of a module rather than having to do it ourselves, which would warrant its own gem.

Once we have a system in place for determining whether the original source code has changed, we could provide a Rake task for validating that all of the application's prependers are still valid. This Rake task could be run in a CI environment to make the build fail if some of the original modules have changed since they were overridden.

Issue Mocking Prepended Class Methods

Ruby: 2.5.3
Prependers: 0.1.1
Rails: 5.2.2

Given the follow file

# app/prependers/models/spree/product/scopes.rb

module Spree::Product::Scopes
  def self.prepended(base)
    base.singleton_class.prepend ClassMethods
  end

  module ClassMethods
    def purchasable
       # some code      
    end
  end
end

When trying to mock Spree::Product.purchasable

  before do
      allow(Spree::Product).to receive_messages(purchasable: purchasable_products)
  end

The follow error is returned AFTER the test has ran

     NameError:
       undefined method `purchasable' for class `#<Class:0x000055b4b3dc3198>'
     # /home/richard/.rvm/gems/ruby-2.5.3/gems/rspec-mocks-3.8.0/lib/rspec/mocks/method_double.rb:108:in `public'
     # /home/richard/.rvm/gems/ruby-2.5.3/gems/rspec-mocks-3.8.0/lib/rspec/mocks/method_double.rb:108:in `restore_original_visibility'
     # /home/richard/.rvm/gems/ruby-2.5.3/gems/rspec-mocks-3.8.0/lib/rspec/mocks/method_double.rb:87:in `restore_original_method'
     # /home/richard/.rvm/gems/ruby-2.5.3/gems/rspec-mocks-3.8.0/lib/rspec/mocks/method_double.rb:118:in `reset'
     # /home/richard/.rvm/gems/ruby-2.5.3/gems/rspec-mocks-3.8.0/lib/rspec/mocks/proxy.rb:319:in `block in reset'
     # /home/richard/.rvm/gems/ruby-2.5.3/gems/rspec-mocks-3.8.0/lib/rspec/mocks/proxy.rb:319:in `each_value'
     # /home/richard/.rvm/gems/ruby-2.5.3/gems/rspec-mocks-3.8.0/lib/rspec/mocks/proxy.rb:319:in `reset'
     # /home/richard/.rvm/gems/ruby-2.5.3/gems/rspec-mocks-3.8.0/lib/rspec/mocks/space.rb:79:in `block in reset_all'
     # /home/richard/.rvm/gems/ruby-2.5.3/gems/rspec-mocks-3.8.0/lib/rspec/mocks/space.rb:79:in `each_value'
     # /home/richard/.rvm/gems/ruby-2.5.3/gems/rspec-mocks-3.8.0/lib/rspec/mocks/space.rb:79:in `reset_all'
     # /home/richard/.rvm/gems/ruby-2.5.3/gems/rspec-mocks-3.8.0/lib/rspec/mocks.rb:52:in `teardown'
     # /home/richard/.rvm/gems/ruby-2.5.3/gems/rspec-core-3.8.0/lib/rspec/core/mocking_adapters/rspec.rb:27:in `teardown_mocks_for_rspec'

When trying to mock via a class_double

    let(:spree_product) { class_double Spree::Product, purchasable: purchasable_products }

The follow error is returned During other tests that are using Spree::Product

  #<ClassDouble(Spree::Product) (anonymous)> was originally created in one example but has leaked into another example and can no longer be used. rspec-mocks' doubles are designed to only last for one example, and you need to create a new one in each example you wish to use it for.

When trying to force reset the mock using

after do
  RSpec::Mocks.space.proxy_for(Spree::Product).reset
end

The follow error is returned AFTER the test has ran

WARNING: RSpec could not fully restore Spree::Product.purchasable, possibly because the method has been redefined by something outside of RSpec. Called from /spec/interactors/concerns/~omitted~/~ommitted~_spec.rb:29:in `block (3 levels) in <top (required)>'.

NameError: undefined method `purchasable' for class `#<Class:0x0000563d345f48e0>'

Maybe related to rspec/rspec-mocks#1218

Add integration tests for Rails

Now that we officially support Rails, it would be great to have integration tests in place that make sure everything works properly both with the classic autoloader and with Zeitwerk, both with and without eager loading.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.