Skip to content

Instantly share code, notes, and snippets.

@dux
Last active October 20, 2023 13:51
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dux/581c860c143ffb17da0037e14159cb43 to your computer and use it in GitHub Desktop.
Save dux/581c860c143ffb17da0037e14159cb43 to your computer and use it in GitHub Desktop.
Simple ruby decorators with example
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
# 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