Skip to content

Instantly share code, notes, and snippets.

@nickcharlton
Created July 16, 2015 07:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nickcharlton/0821ec4304a0e1185a9b to your computer and use it in GitHub Desktop.
Save nickcharlton/0821ec4304a0e1185a9b to your computer and use it in GitHub Desktop.
An example of creating a custom accessor type to parse inputs.
#!/usr/bin/ruby
require 'date'
class Resource
def initialize(hash = {})
hash.each { |k, v| send("#{k}=", v) if respond_to?("#{k}=") }
end
class << self
def date_writer(*args)
args.each do |attr|
define_method("#{attr.to_s}=".to_sym) do |date|
date = date.is_a?(String) ? DateTime.parse(date) : date
instance_variable_set("@#{attr}", date)
end
end
end
def date_accessor(*args)
attr_reader *args
date_writer *args
end
end
end
class Post < Resource
date_accessor :published_at
end
post = Post.new(published_at: '2015-07-16T08:04:31Z')
puts post.published_at
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment