Skip to content

Instantly share code, notes, and snippets.

@tastycode
Created January 10, 2017 17:13
Show Gist options
  • Save tastycode/b277e623c4da3fbf91d87b84c49db312 to your computer and use it in GitHub Desktop.
Save tastycode/b277e623c4da3fbf91d87b84c49db312 to your computer and use it in GitHub Desktop.
MagicStruct
class MagicStruct
include ActiveModel::Validations
def initialize(hashish)
hashish.each do |key, val|
send(:"#{key}=", val)
end
end
def self.required_params(*required_keys)
_required_params |= Array.wrap(required_keys)
required_keys.each(&method(:attr_accessor))
required_keys.each(&method(:validates_presence_of))
end
def self.optional_params(*optional_keys)
_optional_params |= Array.wrap(optional_keys)
optional_keys.each(&method(:attr_accessor))
end
class << self
private
attr_accessor :_required_params, :_optional_params
def _required_params
@required_params ||= []
end
def _optional_params
@optional_params ||= []
end
end
end
class Message < MagicStruct
required_params :subject, :body
optional_params :categories
end
m = Message.new(subject: "foo")
m.valid?
m.subject
class SpecialM < Message
required_params :recipient
end
k = SpecialM.new(recipient: "nana", subject: "foo")
k.valid?
k.body = "woof"
k.valid?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment