Skip to content

Instantly share code, notes, and snippets.

@dux
Last active Jan 8, 2017
Embed
What would you like to do?
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