Skip to content

Commit

Permalink
Merge pull request active-hash#202 from reedlaw/disable-erb
Browse files Browse the repository at this point in the history
add option to disable erb parsing
  • Loading branch information
kbrock authored Mar 13, 2023
2 parents d08e6fb + 91330b4 commit e58f3ff
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 5 deletions.
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -459,6 +459,12 @@ Embedded ruby can be used in ActiveYaml using erb brackets `<% %>` and `<%= %>`
password: <%= ENV['USER_PASSWORD'] %>
```

This can be disabled in an initializer:
```ruby
# config/initializers/active_yaml.rb
ActiveYaml::Base.process_erb = false
```

## ActiveJSON

If you want to store your data in JSON files, just inherit from ActiveJSON and specify your path information:
Expand Down
12 changes: 10 additions & 2 deletions lib/active_yaml/base.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ module ActiveYaml

class Base < ActiveFile::Base
extend ActiveFile::HashAndArrayFiles

cattr_accessor :process_erb, instance_accessor: false
@@process_erb = true

class << self
def load_file
if (data = raw_data).is_a?(Array)
Expand All @@ -20,11 +24,15 @@ def extension
private
if Psych::VERSION >= "4.0.0"
def load_path(path)
YAML.unsafe_load(ERB.new(File.read(path)).result)
result = File.read(path)
result = ERB.new(result).result if process_erb
YAML.unsafe_load(result)
end
else
def load_path(path)
YAML.load(ERB.new(File.read(path)).result)
result = File.read(path)
result = ERB.new(result).result if process_erb
YAML.load(result)
end
end
end
Expand Down
19 changes: 16 additions & 3 deletions spec/active_yaml/base_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,26 @@ class Empty < ActiveYaml::Base ; end # Empty YAML
Object.send :remove_const, :ArrayRow
Object.send :remove_const, :City
Object.send :remove_const, :State
Object.send :remove_const, :User
Object.send :remove_const, :Empty
end

describe ".load_path" do
it 'can execute embedded ruby' do
expect(User.first.email).to match(/^user[0-9]*@email.com$/)
expect(User.first.password).to eq('secret')
context 'default' do
it 'can execute embedded ruby' do
expect(User.first.email).to match /^user[0-9]*@email.com$/
expect(User.first.password).to eq 'secret'
end
end

context 'erb disabled' do
before { ActiveYaml::Base.process_erb = false }
after { ActiveYaml::Base.process_erb = true }

it 'can execute embedded ruby' do
expect(User.first.email).to eq '<%= "user#{rand(100)}@email.com" %>'
expect(User.first.password).to eq "<%= ENV['USER_PASSWORD'] %>"
end
end

it 'can load empty yaml' do
Expand Down

0 comments on commit e58f3ff

Please sign in to comment.