Skip to content

Instantly share code, notes, and snippets.

@Deepwalker
Forked from anonymous/gist:4286580
Created December 14, 2012 16:13
Show Gist options
  • Save Deepwalker/4286583 to your computer and use it in GitHub Desktop.
Save Deepwalker/4286583 to your computer and use it in GitHub Desktop.
типа rabl
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