Created
July 16, 2015 07:10
-
-
Save nickcharlton/0821ec4304a0e1185a9b to your computer and use it in GitHub Desktop.
An example of creating a custom accessor type to parse inputs.
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
#!/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