Skip to content

Blacklight::OpenStructWithHashAccess should expose a HashWithIndifferentAccess #1595

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions lib/blacklight/utils.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# frozen_string_literal: true
require 'ostruct'
require 'active_support/hash_with_indifferent_access'

module Blacklight
module Utils
def self.needs_attr_accessible?
Expand All @@ -11,11 +13,31 @@ def self.protected_attributes_enabled?
end
end

class HashWithIndifferentAccessWithSymbolKeys < ActiveSupport::HashWithIndifferentAccess
protected

def convert_key(key)
if key.is_a?(Symbol)
key
elsif key.respond_to? :to_sym
key.to_sym
else
key
end
end
end

##
# An OpenStruct that responds to common Hash methods
class OpenStructWithHashAccess < OpenStruct
delegate :keys, :each, :map, :has_key?, :key?, :include?, :empty?, :length, :delete, :delete_if, :keep_if, :clear, :reject!, :select!, :replace, :fetch, :to_json, :as_json, to: :to_h

def initialize(*args)
super

@table = HashWithIndifferentAccessWithSymbolKeys.new(@table)
end

##
# Expose the internal hash
# @return [Hash]
Expand Down
3 changes: 1 addition & 2 deletions spec/lib/blacklight/utils_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -38,14 +38,13 @@
end

it "exposes the internal hash table" do
expect(@h.to_h).to be_a_kind_of(Hash)
expect(@h.to_h).to be_a_kind_of(HashWithIndifferentAccess)
expect(@h.to_h[:a]).to eq 1
end

it "exposes keys" do
expect(@h.keys).to include(:a, :b)
end

end

describe "#key?" do
Expand Down