Interactor does not allow to expose hashes with non-symbolizable keys
alexd16 opened this issue · comments
Hi,
I was trying to use the Hanami::Interactor in a rails project and I came across an issue where I cannot expose a hash that does not have symbolizable keys (to_sym not defined).
Example:
class Mapping
include Hanami::Interactor
expose :mapping
def call
@mapping = { 1 => 'Hello' }
end
end
Mapping.new.call
# NoMethodError: undefined method `to_sym' for 1:Fixnum
From what I see the issue is that the exposures in the Interactor is stored in a Utils::Hash and it calls simbolize! here: https://github.com/hanami/utils/blob/master/lib/hanami/interactor.rb#L136.
This will try to convert every keys in the exposures hash and any nested hash to a symbol which will blow up in this case because Fixnum does not have the to_sym method.
I was wondering if this is the intended behaviour and If so if there is work around to implement something like this?
Thank you
@alexd16 Hi! Yes, that isn't the expected way to use it. The returning value of #call
is meant to be a symbolized hash.
May I ask you what's your real world use case? Thanks
Hi @jodosha! Thanks for the response.
About my use case, I need to render an excel type grid in the frontend.
This grid is used to join two models and assign a certain float value.
So the easiest way I found to fill the initial values of the grid was to build an hash with ids of one of the models mapping to the ids of the other model with the value that should appear in the respective cell. For example:
mapping: {
1: {
5: 2.0,
7: 1.0
},
10: {
1: 0.5,
12: 1.4
}
}
So I was trying to use an interactor to build the hash and expose it to the controller.
Not sure if this is a scenario where I should use an Interactor or not.
What do you think?
If something is not clear let me know. Thks
PS: Sorry to bother you with this.
PS: Sorry to bother you with this.
No worries at all.
Now I see your problem. It's because Interactor uses Utils::Hash#symbolize!
for result. Unfortunately that Utils::Hash
method deep symbolizes all the keys, which is unexpected.
The intent here is to just symbolize the keys of result:
Hanami::Interactor::Result.new("foo" => { "bar" => "baz" })
In the example above only "foo"
should be symbolized, not the nested hash.
Yeah I saw the reason why it was happening I just wasn't sure if it was the intended behaviour.
If you want I can try to make a PR for it.