Skip to content

Commit

Permalink
Add #to_h method
Browse files Browse the repository at this point in the history
(cherry picked from commit c7ec35291dc89b68351a059eec8fd66669ecf1e9)
  • Loading branch information
palkan committed Oct 6, 2017
1 parent 2bc8ebf commit aa2c21f
Show file tree
Hide file tree
Showing 4 changed files with 85 additions and 0 deletions.
8 changes: 8 additions & 0 deletions lib/anyway/config.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@

require 'anyway/ext/class'
require 'anyway/ext/deep_dup'
require 'anyway/ext/deep_freeze'
require 'anyway/ext/hash'

module Anyway # :nodoc:
using Anyway::Ext::Class
using Anyway::Ext::DeepDup
using Anyway::Ext::DeepFreeze
using Anyway::Ext::Hash

# Base config class
Expand Down Expand Up @@ -95,6 +97,12 @@ def load_from_env(config)
config
end

def to_h
self.class.config_attributes.each_with_object({}) do |key, obj|
obj[key.to_sym] = send(key)
end.deep_dup.deep_freeze
end

private

def set_value(key, val)
Expand Down
26 changes: 26 additions & 0 deletions lib/anyway/ext/deep_freeze.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# frozen_string_literal: true

module Anyway
module Ext
# Add #deep_freeze to hashes and arrays
module DeepFreeze
refine ::Hash do
def deep_freeze
freeze
each_value do |value|
value.deep_freeze if value.is_a?(::Hash) || value.is_a?(::Array)
end
end
end

refine ::Array do
def deep_freeze
freeze
each do |value|
value.deep_freeze if value.is_a?(::Hash) || value.is_a?(::Array)
end
end
end
end
end
end
19 changes: 19 additions & 0 deletions spec/config_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,25 @@
expect(conf).to respond_to(:user)
end

describe "#to_h" do
subject(:config) { CoolConfig.new }

it "returns deeply frozen hash" do
hashed = config.to_h

expect(hashed).to be_a(Hash)
expect(hashed).to be_frozen
expect(hashed[:user]).to be_frozen
end

it "returns new hash every time" do
hashed = config.to_h
hashed2 = config.to_h

expect(hashed).to be_eql(hashed2)
end
end

describe "load from files" do
it "set defaults" do
expect(conf.port).to eq 8080
Expand Down
32 changes: 32 additions & 0 deletions spec/ext/deep_freeze_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# frozen_string_literal: true

require 'spec_helper'
require 'anyway/ext/deep_freeze'

describe Anyway::Ext::DeepFreeze do
using Anyway::Ext::DeepFreeze

it "freezes nested arrays and hashes", :aggregate_failures do
source = {
a: 1,
b: 'hello',
c: {
id: 1,
list: [1, 2, { name: 'John' }]
},
d: [{ id: 1 }, { id: 2 }]
}

dup = source.deep_freeze

expect(dup).to be_frozen
expect(dup[:c]).to be_frozen
expect(dup[:d]).to be_frozen

expect(dup[:c][:list]).to be_frozen
expect(dup[:c][:list].last).to be_frozen

expect(dup[:d].first).to be_frozen
expect(dup[:d].last).to be_frozen
end
end

0 comments on commit aa2c21f

Please sign in to comment.