Last active
May 31, 2016 14:29
-
-
Save ch1ago/82df70195e2c4c83544a374154174d6a to your computer and use it in GitHub Desktop.
hash decorators
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
# app/nfe/base.rb | |
module Nfe | |
class Base | |
def self.array(array) | |
array.map { |hash| new(hash) } | |
end | |
def initialize(hash) | |
@hash = hash.stringify_keys | |
end | |
def method_missing(method, *args, &block) | |
if @hash.has_key?(method) | |
@hash[method] | |
else | |
super | |
end | |
end | |
end | |
end | |
# app/nfe/item_produto.rb | |
module Nfe | |
class ItemProduto < Base | |
def det_icm_picms | |
parse_f(@hash['det_icm_picms']) | |
end | |
def det_ipi_pipi | |
parse_f(@hash['det_ipi_pipi']) | |
end | |
private | |
def parse_f(x) | |
x = x.to_f | |
x.zero? ? "0,00" : x | |
end | |
end | |
end | |
# rails console | |
Nfe::ItemProduto.new(det_icm_picms: 10).det_icm_picms | |
Nfe::ItemProduto.new(det_icm_picms: '').det_icm_picms | |
Nfe::ItemProduto.new(det_icm_picms: 0).det_icm_picms | |
Nfe::ItemProduto.new(det_icm_picms: 10).det_ipi_pipi | |
Nfe::ItemProduto.new(det_icm_picms: 10).foo | |
# array = @hash_nfe_proc["items_produtos"] | |
array = [{det_icm_picms: 10}, {det_icm_picms: 20}] | |
Nfe::ItemProduto.array(array).each do |item_produto| | |
puts item_produto.det_icm_picms | |
puts item_produto.det_ipi_pipi | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment