Created
December 14, 2012 16:12
-
-
Save anonymous/4286580 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
module AngryData | |
class Attribute | |
def initialize(name, options = {}, &blk) | |
@name = name | |
@options = options | |
@blk = blk | |
end | |
def name | |
@name.to_s | |
end | |
def get(obj) | |
if @blk | |
return @blk.call obj | |
end | |
data = begin | |
obj.send(@name) | |
rescue NameError | |
nil | |
end | |
data ||= begin | |
obj[@name] || obj[@name.to_s] | |
rescue NoMethodError, TypeError | |
nil | |
end | |
end | |
alias :dump :get | |
end | |
class Array < Attribute | |
def dump(obj) | |
cls = @options[:class] | |
if data = get(obj) | |
data.map do |elem| | |
cls.dump elem | |
end | |
else | |
[] | |
end | |
end | |
end | |
class Hash < Attribute | |
def initialize(name = nil, options = {}, &blk) | |
@name = name | |
@options = options | |
@attrs = options[:attributes] || [] | |
instance_eval(&blk) | |
end | |
def attribute(name, options = {}, &blk) | |
@attrs << Attribute.new(name, options, &blk) | |
end | |
def array(name, options = {}, &blk) | |
@attrs << Array.new(name, options, &blk) | |
end | |
def hash(name, options = {}, &blk) | |
@attrs << Hash.new(name, options = {}, &blk) | |
end | |
def dump(obj) | |
res = {} | |
data = if @name then get(obj) else obj end | |
@attrs.each do |attr| | |
res[attr.name] = attr.dump(data) | |
end | |
res | |
end | |
end | |
end | |
# -*- coding: utf-8 -*- | |
require 'spec_helper' | |
require 'angry_data' | |
describe AngryData do | |
Provider = AngryData::Hash.new do | |
attribute :url | |
end | |
Checker = AngryData::Hash.new do | |
attribute :name | |
array :providers, class: Provider do |obj| | |
obj['oa'].flat_map do |prov_name, accs| | |
accs.map {|uuid, data| data} | |
end | |
end | |
end | |
let :raw do | |
{'name' => 'kuku', | |
'oa' => { | |
'facebook' => { | |
'124234234234234' => {'url' => 'http://ya.ru'}, | |
'124234234234235' => {'url' => 'http://www.ru'} | |
} | |
} | |
} | |
end | |
it 'должно работать' do | |
Checker.dump(raw).must_equal({"name"=>"kuku", "providers"=>[{"url"=>"http://ya.ru"}, {"url"=>"http://www.ru"}]}) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment