Browse Source

Allow Base Model to be initialized from geojson hash

develop
Bèr Kessels 3 months ago
parent
commit
48820f91f4
3 changed files with 46 additions and 5 deletions
  1. 10
    2
      app/models/base.rb
  2. 6
    3
      app/models/base_collection.rb
  3. 30
    0
      test/models/base_test.rb

+ 10
- 2
app/models/base.rb View File

@@ -5,11 +5,19 @@ module Hours
##
# Base model that can read from a query database
class Base
def initialize(attributes = {})
def initialize(attributes = {}, ignore_undefined_attributes = false)
attributes.each do |key, value|
send("#{key}=", value)
setter = "#{key}="
send(setter, value)
rescue NoMethodError
raise unless ignore_undefined_attributes
end
end

def self.from_geojson_feature(feature)
attrs = feature.properties.fetch('geocoding', {})
new(attrs, true)
end
end
end
end

+ 6
- 3
app/models/base_collection.rb View File

@@ -24,10 +24,13 @@ module Hours

def each
@dataset.each do |row|
if row
yield self.class::ITEM_CLASS.new(row)
else
case row
when NilClass
yield self.class::NULLITEM_CLASS.new
when Hash
yield self.class::ITEM_CLASS.new(row)
when RGeo::GeoJSON::Feature
yield self.class::ITEM_CLASS.from_geojson_feature(row)
end
end
end

+ 30
- 0
test/models/base_test.rb View File

@@ -4,4 +4,34 @@ require 'test_helper'
require_relative Hours.base_path.join 'app/models/base.rb'

describe Hours::Models::Base do
class MockModel < Hours::Models::Base
attr_accessor :name
end

describe '.initialize' do
it 'sets accessible attributes' do
subject = MockModel.new(name: 'Hi')
assert_equal 'Hi', subject.name
end

it 'raises on undefined methods' do
assert_raises NoMethodError do
MockModel.new(fakemethod: 'val')
end
end
end

describe '.from_geojson_feature' do
let(:feature) do
OpenStruct.new(
properties: { 'geocoding' => { 'name' => 'Hi', 'fakemethod' => 'val' } }
)
end

it 'ignores undefined attributes' do
subject = MockModel.from_geojson_feature(feature)
# Does not raise NoMethodError
assert_equal 'Hi', subject.name
end
end
end

Loading…
Cancel
Save