Last active
October 20, 2023 13:51
-
-
Save dux/581c860c143ffb17da0037e14159cb43 to your computer and use it in GitHub Desktop.
Simple ruby decorators with example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class DecoratorClone | |
def initialize(model) | |
@model = model | |
end | |
def method_missing(m, *args) | |
raise NameError, "Decorator method '#{m}' not found" unless @model.respond_to?(m) | |
@model.send(m, *args) | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# ApplicationModel = Class.new(Sequel::Model) | |
# ApplicationModel < ActiveRecord::Base | |
class ApplicationModel | |
def dec | |
@decorated_dup ||= Proc.new { DecoratorClone.new(self).extend "#{self.class}Decorator".constantize }.call | |
end | |
end | |
# this is user model decorator | |
module UserDecorator | |
def full_name | |
"#{first_name} #{last_name}" | |
end | |
end | |
# user has db fields :first_name and :last_name | |
class User < ApplicationModel | |
end | |
user = User.last | |
user.dec.full_name # => John Smith | |
user.full_name # => NameError | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment