Skip to content

Instantly share code, notes, and snippets.

@yhirano55
Last active December 7, 2017 08:06
Show Gist options
  • Save yhirano55/b3eb88c05877fb27b0b08de043317c51 to your computer and use it in GitHub Desktop.
Save yhirano55/b3eb88c05877fb27b0b08de043317c51 to your computer and use it in GitHub Desktop.
関心事の分離とアンチパターン ref: https://qiita.com/yhirano55/items/92ba558bcb19f3a1f233
class Todo < ApplicationRecord
# Other todo implementation
# ...
## Event tracking
has_many :events
before_create :track_creation
after_destroy :track_deletion
private
def track_creation
# ...
end
end
class Todo < ApplicationRecord
# Other todo implementation
# ...
module EventTracking
extend ActiveSupport::Concern
included do
has_many :events
before_create :track_creation
after_destroy :track_deletion
end
private
def track_creation
# ...
end
end
include EventTracking
end
class Todo < ApplicationRecord
# Other todo implementation
# ...
include TodoEventTracking
end
class Todo
# Other todo implementation
# ...
concerning :EventTracking do
included do
has_many :events
before_create :track_creation
after_destroy :track_deletion
end
private
def track_creation
# ...
end
end
end
Todo.ancestors
# => Todo, Todo::EventTracking, Object
class Module
module Concerning
# Define a new concern and mix it in.
def concerning(topic, &block)
include concern(topic, &block)
end
def concern(topic, &module_definition)
const_set topic, Module.new {
extend ::ActiveSupport::Concern
module_eval(&module_definition)
}
end
end
include Concerning
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment