Tuesday, August 16, 2016

Using Braintree's v.zero SDK to accept payments


Tired of Ruby's modules not allowing you to mix in class methods easily? Tired of writing complex self.included(base) code or using over-engineered solutions like ActiveSupport::Concern to accomplish that goal?

Well, worry no more! SuperModule comes to the rescue!

SuperModule allows defining class methods and method invocations the same way a super class does without using self.included(base).

This succeeds ActiveSupport::Concern by offering lighter syntax and simpler module dependency support.

Introductory Comparison

To introduce SuperModule, here is a comparison of three different approaches for writing a UserIdentifiable module.

1) self.included(base)
  1. module UserIdentifiable
  2.   include ActiveModel::Model

  3.   def self.included(base_klass)
  4.     base_klass.extend(ClassMethods)
  5.     base.class_eval do
  6.       belongs_to :user
  7.       validates :user_id, presence: true
  8.     end
  9.   end

  10.   module ClassMethods
  11.     def most_active_user
  12.       User.find_by_id(select('count(id) as head_count, user_id').group('user_id').order('count(id) desc').first.user_id)
  13.     end
  14.   end

  15.   def slug
  16.     "#{self.class.name}_#{user_id}"
  17.   end
  18. end
This is a lot to think about and process for simply wanting inclusion of class method definitions (like most_active_user) and class method invocations (like belongs_to and validates). The unnecessary complexity gets in the way of problem-solving; slows down productivity with repetitive boiler-plate code; and breaks expectations set in other similar object-oriented languages, discouraging companies from including Ruby in a polyglot stack, such as Groupon's Rails/JVM/Node.js stack and SoundCloud's JRuby/Scala/Clojure stack.

2) ActiveSupport::Concern
  1.  module UserIdentifiable
  2.   extend ActiveSupport::Concern
  3.   include ActiveModel::Model

  4.   included do
  5.     belongs_to :user
  6.     validates :user_id, presence: true
  7.   end

  8.   module ClassMethods
  9.     def most_active_user
  10.       User.find_by_id(select('count(id) as head_count, user_id').group('user_id').order('count(id) desc').first.user_id)
  11.     end
  12.   end

  13.   def slug
  14.     "#{self.class.name}_#{user_id}"
  15.   end
  16. end
A step forward that addresses the boiler-plate repetitive code concern, but is otherwise really just lipstick on a pig. To explain more, developer problem solving and creativity flow is still disrupted by having to think about the lower-level mechanism of running code on inclusion (using included) and structuring class methods in an extra sub-module (ClassMethods) instead of simply declaring class methods like they normally would in Ruby and staying focused on the task at hand.

3) SuperModule
  1. module UserIdentifiable
  2.   include SuperModule
  3.   include ActiveModel::Model

  4.   belongs_to :user
  5.   validates :user_id, presence: true

  6.   def self.most_active_user
  7.     User.find_by_id(select('count(id) as head_count, user_id').group('user_id').order('count(id) desc').first.user_id)
  8.   end

  9.   def slug
  10.     "#{self.class.name}_#{user_id}"
  11.   end
  12. end
With include SuperModule declared on top, developers can directly add class method invocations and definitions inside the module's body, and SuperModule takes care of automatically mixing them into classes that include the module.

As a result, SuperModule collapses the difference between extending a super class and including a super module, thus encouraging developers to write simpler code while making better Object-Oriented Design decisions.

In other words, SuperModule furthers Ruby's goal of making programmers happy.

Instructions

1) Install and require gem

Using Bundler

Add the following to Gemfile:
  1. gem 'super_module', '1.0.0'
And run the following command:
  1. bundle
Afterwards, SuperModule will automatically get required in the application (e.g. a Rails application) and be ready for use.

Using RubyGem Directly

Run the following command:
  1. gem install super_module
(add --no-ri --no-rdoc if you wish to skip downloading documentation for a faster install)

Add the following at the top of your Ruby file:
  1. require 'super_module'
2) Include SuperModule at the top of the module
  1. module UserIdentifiable
  2.   include SuperModule
  3.   include ActiveModel::Model

  4.   belongs_to :user
  5.   validates :user_id, presence: true

  6.   def self.most_active_user
  7.     User.find_by_id(select('count(id) as head_count, user_id').group('user_id').order('count(id) desc').first.user_id)
  8.   end

  9.   def slug
  10.     "#{self.class.name}_#{user_id}"
  11.   end
  12. end
3) Mix newly defined module into a class or another super module
  1. class ClubParticipation < ActiveRecord::Base
  2.   include UserIdentifiable
  3. end
  4. class CourseEnrollment < ActiveRecord::Base
  5.   include UserIdentifiable
  6. end
  7. module Accountable
  8.   include SuperModule
  9.   include UserIdentifiable
  10. end
  11. class Activity < ActiveRecord::Base
  12.   include Accountable
  13. end
4) Start using by invoking class methods or instance methods
  1. CourseEnrollment.most_active_user
  2. ClubParticipation.most_active_user
  3. Activity.last.slug
  4. ClubParticipation.create(club_id: club.id, user_id: user.id).slug
  5. CourseEnrollment.new(course_id: course.id).valid?
Glossary and Definitions
  • SuperModule: name of the library and Ruby module that provides functionality via mixin
  • Super module: any Ruby module that mixes in SuperModule
  • Class method definition: Ruby class or module method declared with self.method_name or class << self
  • Class method invocation: Inherited Ruby class or module method invoked in the body of a class or module (e.g. validates :username, presence: true)
  • Code-time: Time of writing code in a Ruby file as opposed to Run-time
  • Run-time: Time of executing Ruby code
Usage Details
  • SuperModule must always be included at the top of a module's body at code-time
  • SuperModule inclusion can be optionally followed by other basic or super module inclusions
  • A super module can only be included in a class or another super module
  • SuperModule adds zero cost to instantiation of including classes and invocation of included methods (both class and instance)
How Does It Work?

Here is the general algorithm from the implementation:
  1. def included(base)
  2.   __invoke_super_module_class_method_calls(base)
  3.   __define_super_module_class_methods(base)
  4. end
  1. 1) Invoke super module class method calls on the including base class.
For example, suppose we have a super module called Locatable:
  1. module Locatable
  2.   include SuperModule

  3.   validates :x_coordinate, numericality: true
  4.   validates :y_coordinate, numericality: true

  5.   def move(x, y)
  6.     self.x_coordinate += x
  7.     self.y_coordinate += y
  8.   end
  9. end

  10. class Vehicle < ActiveRecord::Base
  11.   include Locatable
  12. # … more code follows
  13. end
This first step guarantees invocation of the two Locatable validates method calls on the Vehicle object class.
It does so by relying on method_missing(method_name, *args, &block) to record every class method call that happens in the super module class body, and later replaying those calls on the including base class during self.included(base) by using Ruby's send(method_name, *args, &block) method introspection.

2) Defines super module class methods on the including base class

For example, suppose we have a super module called Addressable:
  1. module Addressable
  2.   include SuperModule

  3.   include Locatable
  4.   validates :city, presence: true, length: { maximum: 255 }
  5.   validates :state, presence: true, length: { is: 2 }

  6.   def self.merge_duplicates
  7.     # 1. Look through all Addressable instances in the database
  8.     # 2. Identify duplicates
  9.     # 3. Merge duplicate addressables
  10.   end
  11. end

  12. class Contact < ActiveRecord::Base
  13.   include Addressable
  14. # … more code follows
  15. end
The second step ensures that merge_duplicates is included in Contact as a class method, allowing the call Contact.merge_duplicates

It does so by recording every class method defined using the self.singleton_method_added(method_name) added hook, and then later replaying these class definitions on the including base class during invocation of self.included(base).

In order to avoid interference with existing class method definitions, there is an exception list for what not to record, such as includedmethod_missingsingleton_method_added, and any other "__" prefixed class method defined in SuperModule (e.g. __super_module_class_method_calls).

Limitations and Caveats
  • SuperModule has been designed to be used only in the code definition of a module, not to be mixed in at run-time.
  • Initial Ruby runtime load of a class or module mixing in SuperModule will incur a very marginal performance hit (in the order of nano-to-milliseconds). However, class usage (instantiation and method invocation) will not incur any performance hit, running as fast as any other Ruby class.
  • Given SuperModule relies on self.included(base) in its implementation, if an including super module (or a super module including another super module) must hook into self.included(base)for meta-programming cases that require it, such as conditional include statements or method definitions, it would have to alias self.included(base) and then invoke the aliased version in every super module that needs it like in this example:
  1. module AdminIdentifiable
  2.  include SuperModule
  3.  include UserIdentifiable

  4.  class << self
  5.      alias included_super_module included
  6.      def included(base)
  7.          included_super_module(base)
  8.          # do some extra work 
  9.          # like conditional inclusion of other modules
  10.          # or conditional definition of methods
  11.      end
  12.  end
In the future, SuperModule could perhaps provide robust built-in facilities for allowing super modules to easily hook into self.included(base) without interfering with SuperModule behavior.
Given SuperModule relies on method_missing(method_name, args, &block) inside class << self, a super module including it that needs to do some additional method_missing (method_missing(method_name, args, &block) meta-programming must not only alias it, but also be mindful of implications on SuperModule behavior.

Feedback and Contribution

SuperModule is written in a very clean and maintainable test-first approach, so you are welcome to read through the code on GitHub for more in-depth details: 
https://github.com/AndyObtiva/super_module

The library is quite new and can use all the feedback and help it can get. So, please do not hesitate to add comments if you have any, and please fork the project on GitHub in order to make contributions via Pull Requests.
Written by Andy Maleh 

If you found this post interesting, follow and support us.
Suggest for you:

No comments:

Post a Comment