Insane Rails problem

Hi,
I’ve a problem

message = params[:message].to_unsafe_h
  logger.debug message[:text] # returns the text message correctly
  if message[:chat][:type] == ‘group’ || message[:chat][:type] == ‘supergroup’
      if message[:text] =~ /asd/i # NO METHOD ERROR, UNDEFINED METHOD [] FOR NIL:NilClass

Are you kidding me?

Any of you have any ideas?

This is insane
My application was API-only, I modified it to work with assets and make it a normal rails app and now there’s this problem
I’ve spent an hour trying to figure WHY and I didn’t understand

D, [2019-08-11T15:39:14.952504 #13713] DEBUG -- : [56fbc12a-ad66-46d6-956d-94870d3ca0ec] NOW MESSAGE
D, [2019-08-11T15:39:14.955103 #13713] DEBUG -- : [56fbc12a-ad66-46d6-956d-94870d3ca0ec] --- !ruby/hash:ActiveSupport::HashWithIndifferentAccess
update_id: 200421708
edited_message: !ruby/hash:ActiveSupport::HashWithIndifferentAccess
message_id: 37769
from: !ruby/hash:ActiveSupport::HashWithIndifferentAccess
  id: 85039287
  is_bot: false
  first_name: Dennis
  last_name: Radaelli
  username: Radden
chat: !ruby/hash:ActiveSupport::HashWithIndifferentAccess
  id: -1001447558052
  title: WIKINETWORK OT - FERDINANDO PADANIA VI FANNO IMPAZZIRE
  type: supergroup
date: 1565477411
edit_date: 1565477416
text: Vada! Vada!

Thanks for the help.

I am not into Rails. Generally when you are calling the [key_object] method on a hash, it returns the value referring to the key_object.
But when it can’t find the key, it returns the default value. So as far as I understood, something like this is happening:

> hash = {a: {x: 1}, b: {y: 2}, c: {z: 3}}
=> {:a=>{:x=>1}, :b=>{:y=>2}, :c=>{:z=>3}}

> hash[:a][:x]
=> 1

> hash.dig(:a, :x)
=> 1

> hash[:d][:y]    # There's no :d key in the hash
Traceback (most recent call last):
        2: from /home/sourav/.irb:350:in `<main>'
        1: from (irb):15
NoMethodError (undefined method `[]' for nil:NilClass)
irb(main):016:0> hash[:d].to_h[:y]
=> nil

To avoid that, you can either:

> hash = {a: {x: 1}, b: {y: 2}, c: {z: 3}}
=> {:a=>{:x=>1}, :b=>{:y=>2}, :c=>{:z=>3}}

irb(main):018:0> hash[:d].to_h[:y]
=> nil

Or:

> hash = {a: {x: 1}, b: {y: 2}, c: {z: 3}}
=> {:a=>{:x=>1}, :b=>{:y=>2}, :c=>{:z=>3}}

> hash.default = {}
=> {}

> hash[:d][:y]
=> nil

Or:

> hash = {a: {x: 1}, b: {y: 2}, c: {z: 3}}
=> {:a=>{:x=>1}, :b=>{:y=>2}, :c=>{:z=>3}}

> hash.fetch(:d){ {} }[:y]
=> nil

But in your case, you may try to_h method on the message variable so it will force convert it to a hash if it’s nil or even if it’s a hash. The to_h method will create a new hash and GC will discard it when your job is done…

Sorry this was just an attempt. Any other RoR professional would guide you better…

Thanks, but it seems it didn’t worked :frowning: also because the value there’s. I’m on the verge of collapse.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs