Skip to content

Instantly share code, notes, and snippets.

@oinak
Last active April 5, 2018 14:55
Show Gist options
  • Save oinak/e861114887835468c963 to your computer and use it in GitHub Desktop.
Save oinak/e861114887835468c963 to your computer and use it in GitHub Desktop.
After some twitter discussion we evaluate our different module strategies
# Scope of the debate:
# - not managing state, use class for that
# - not using namescoped classes for faux provacy, plain class is prefereable for that
# - alternative to typical module such as:
module M
def self.included(base)
base.extend ClassMethods
base.class_eval do
scope :disabled, -> { where(disabled: true) }
end
end
module ClassMethods
...
end
end
## When used for including (in Rails):
module SomeResponsabilityConcern
extend AvtiveSupport::Concern
included do
has_many :foos
belongs_to :bar
end
class_methods do
#...
end
def instance_method_one
end
end
# Pros:
# - easy
# - syntax sugar (included do...end instead of module ClassMethods + extend)
# Cons:
# - it adds behaviour into the controller (not very SRP)
# - it hides ruby you might not know well enough hiding its side effects
## When not including:
module TematicFunctions
def public_method
# other_meth can't be called
end
module_function :public_method
private
def other_meth
end
end
# Pros:
# - just ruby
# - recommended by ruby-code-style-guide / ruboto
# Cons:
# - only public module level functions are easy to use
module SegregatedLogic
extend self # public function available at module level
def pub_goer
puts "#{investigator} is the best"
end
private
def investigator
print 'Magnum'
end
end
# Pros:
# - just ruby
# - public functions access private auxiliars
# - recommended by practicing-ruby https://practicingruby.com/articles/uses-for-modules-4
# Cons:
# - "extend self" non obvious for learners
# Example:
# SegregatedLogic.pub_goer
# => Magnum is the best
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment