Skip to content

Commit 4b57213

Browse files
andrii-novikovbezrukavyi
authored andcommitted
add block to convert attrbute (#1)
* add block to convert attrbute * Update .gitignore
1 parent 43af0c2 commit 4b57213

File tree

4 files changed

+15
-11
lines changed

4 files changed

+15
-11
lines changed

.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -10,3 +10,4 @@
1010
# rspec failure tracking
1111
.rspec_status
1212
vendor/bundle
13+
.idea/

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ class Network < ApiStruct::Entity
4747
client_service NetworkClient
4848

4949
attr_entity :name, :id
50+
attr_entity :state, &:to_sym
5051

5152
has_entity :super_admin, as: User
5253
end

api_struct.gemspec

+2-2
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@ require 'api_struct/version'
55
Gem::Specification.new do |spec|
66
spec.name = 'api_struct'
77
spec.version = ApiStruct::VERSION
8-
spec.authors = ['bezrukavyi']
9-
spec.email = ['[email protected]']
8+
spec.authors = ['bezrukavyi', 'andy1341']
9+
1010

1111
spec.summary = 'Api entities'
1212
spec.description = 'Api entities'

lib/api_struct/entity.rb

+11-9
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,15 @@ class Entity < SimpleDelegator
44
extend Extensions::ApiClient
55

66
class << self
7-
attr_accessor :entity_attributes
7+
def entity_attributes
8+
@entity_attributes ||= []
9+
end
810

9-
def attr_entity(*attrs)
10-
@entity_attributes = attrs
11+
def attr_entity(*attrs, &block)
12+
entity_attributes.concat attrs
1113

12-
entity_attributes.each do |attr|
13-
define_entity_attribute_getter(attr)
14+
attrs.each do |attr|
15+
define_entity_attribute_getter(attr, &block)
1416
define_entity_attribute_setter(attr)
1517
end
1618
end
@@ -43,7 +45,7 @@ def convert_to_entity(item, entity_type = self)
4345

4446
def define_entity_attribute_getter(attr)
4547
define_method attr.to_s do
46-
entity[attr]
48+
block_given? ? yield(entity[attr]) : entity[attr]
4749
end
4850
end
4951

@@ -56,7 +58,7 @@ def define_entity_attribute_setter(attr)
5658

5759
attr_reader :entity, :entity_status
5860

59-
def initialize(entity, status = true)
61+
def initialize(entity, entity_status = true)
6062
raise EntityError, "#{entity} must be Hash" unless entity.is_a?(Hash)
6163
@entity = Hashie::Mash.new(extract_attributes(entity))
6264
@entity_status = entity_status
@@ -73,8 +75,8 @@ def failure?
7375

7476
private
7577

76-
def extract_attributes(entity_attributes)
77-
entity_attributes.select { |key, value| self.class.entity_attributes.include?(key.to_sym) }
78+
def extract_attributes(attributes)
79+
attributes.select { |key, _value| self.class.entity_attributes.include?(key.to_sym) }
7880
end
7981
end
8082

0 commit comments

Comments
 (0)