Ruby how to call a class setter with yield - ruby

I was able to get my code working, but I don't like the way it works syntaxually - not sure if that is even a word.
My code currently:
user.set_phone(phone) do
message = "Verify your phone number #{#host}/phone/verify?id=#{user.id}&code=#{user.phone_verification_code}"
CoreIntegrations::Sinch.send_text(message, phone)
end
How I would like it to look/work:
user.phone=(phone) do
message = "Verify your phone number #{#host}/phone/verify?id=#{user.id}&code=#{user.phone_verification_code}"
CoreIntegrations::Sinch.send_text(message, phone)
end
This is the Error I'm getting
/Users/christianjuth/Desktop/apollo-8/app/controllers/application_controller.rb:140: syntax error, unexpected keyword_do, expecting keyword_end /Users/christianjuth/Desktop/apollo-8/app/controllers/application_controller.rb:267: syntax error, unexpected keyword_end, expecting end-of-input
The line number might in sync with the repo, case I have some local changes made to the application controller.
...Or something along those lines. user is an ActiveRecord model. The reason I want to do this, is yield only gets called if the variable phone sent into user.phone= is different from the existing value of user.phone.
I think this is more of a syntax issue, but just in case here is repo for context. The code you are looking at lives in app/controllers/application_controller.rb, and the user model can be found in user/models/user.rb.
UPDATE: I am having trouble calling the setter with yield not defining it. Sorry for the confusion.

If you change the method from def set_phone to def phone= then will be more difficult to invoke, but still possible:
user.send :phone=, phone do
# ...
end

Related

How to Write mock of method using with to send params

Hi I want to know how can I write rspec for the following
def find_user(content)
user = User.find(content.to_i) ||
User.find(email: content) rescue
nil
end
I tried writing
It "user with user name" do
expect(User).to receive(:find).with(email: "test#a.com").and_return(user)
End
But I am gettig error saying
Argument Error
Block not Passed
Can someone please tell what am i missing
I may look first at your code here.
def find_user(content)
user = User.find(content.to_i) ||
User.find(email: content) rescue
nil
end
What is content? I looks like you're expecting either a user_id or an email address.
Doing this from the console:
irb(main):080:0> User.find("email#email.com".to_i)
=> ActiveRecord::RecordNotFound (Couldn't find User with 'id'=0)
So it seems as if having a generic find_user method may be contributing to some of the test writing confusion.
Many times, overly complex tests point to overly complex code.
Perhaps you need one method
find_user_by_email(email)
and another
find_user_by_id(id)
Also, refer to https://api.rubyonrails.org/v6.1.3.2/classes/ActiveRecord/FinderMethods.html#method-i-find_by
It will automatically return nil if nothing is found.
Start there, And then like the other commenters, then post your class, and the spec and we can go from there.

Ruby Sinatra Upload Form params Disturbed

Upon submitting a form in Sinatra, I'm coming up with the following error:
App 40327 output: 2018-06-28 02:59:17 - NoMethodError - undefined method `[]' for nil:NilClass:
App 40327 output: /Library/WebServer/Documents/blammo/routes/publish.rb:87:in `block in <class:MyApp>'
The form is a file upload form, and a single text field. Simple. The file goes through, as does the text field. They are both captured just fine.
I submit the params to a method, which is ultimately responsible for generating the error on the following line down the page:
fname = params[:s_single_file_upload][:filename]
The method in question returns fine with a boolean. I've rewritten it a couple of ways and flushed out anything that might trip something I'm
unfamiliar with.
So the params is messed up if this method mentioned above is being called. So fname can't be assigned. I expect the params to be intact
at this point in the code. Is there any destruction if the params are perused before this point? In another language, I've seen params destroyed
in one way or another for some reason, but I'm not sure about Ruby.
I'm not finding any nil:NilClass, but that's exactly what it's reporting. Here's the trigger of this method:
result = Alpha::rf_alpha_sniff(params)
And the module::method:
module Alpha
def self.rf_alpha_sniff(incoming)
qualifiers = %w(alpha bravo charlie delta echo foxtrot)
incoming.delete('captures')
incoming.delete('splat') # take out Mustermann's 'captures' and 'splat'
incoming.delete('s_single_file_upload') # non-perusal 'single_file_upload'
incoming.values.each do |item|
item = item.gsub(" ","_")
Dev::hq_log("item: #{ qualifiers.include?(item.downcase) }")
return true if qualifiers.include?(item.downcase)
end
return false
end
end
So the page progresses fine without this method. When the method is induced any way, the params seem to get screwed up, so the file is pretty much
gone.
How is this method interfering with the params so that it's unavailable later on down the script? I'm expecting it to be fully available everywhere.
Turns out, using incoming.delete was deleting items from the params hash, as it was a reference to the original, instead of using a copy.
So, I have to copy the params by using params.dup (duplicate) so they are not the same object.
Having a view of the params hash post-testing-method, showed me that objects were indeed deleted. Another one solved.

JSON::ParserError (399: unexpected token at

when I'm going to parse this:
Product = [{"Productname":"Acer 18.5" LED Monitor}]
with Ruby JSOn, its showing me the error JSON::ParserError (399: unexpected token at. I know this is for 18.5" in the string. How can I parse this string?
You have to give the string like this
Product = [{"productname":%q{"Acer 18.5" LED Monitor}}]
If you have an issue with Mongoid + Devise add this to your User model (bug page):
def to_key
id.to_s
end
In your /app/views/layouts/application.html.erb lines 5 and 6, change the first parameter from application to default.
I met the same problem, too for my situation, after changing it the problem was resolved happens on Windows. The parameter application works on the web server.

Ruby Koans about_methods line 123 object loop

Each time I add in the correct code, it gives me the same error due to AboutMethods:0x00000101841a28 number changing each time. It's like its stuck and I don't know how to get out this loop. It worked once, then I went on to the next step, but then it triggered an error after that.
I must not be inputting the correct line of code given from the console?
def test_calling_private_methods_with_an_explicit_receiver
exception = assert_raise(NoMethodError) do
self.my_private_method
end
assert_match "private method `my_private_method' called for #<AboutMethods:0x000001008debf8>", exception.message
end
The AboutMethods:0x000001008debf8 changes each time, not sure how to approach this problem?
AboutMethods:0x... is the output of the inspect method, which usually (and in this case) includes the class name (AboutMethods) and the object id (0x...). The object id is related to the objects location in memory, so it will change every time.
In my experience, there is very little value to checking the string from an exception (it's brittle). However, if you feel the need, use a regex:
assert_match /private method `my_private_method' called for \#\<AboutMethods:.*/

Rails: ParameterFilter::compiled_filter tries to dup symbol

I'm running rails3 with rails exception-notifier gem. When an exception occurs, and an email should be sent, I'm getting an exception from the ParameterFilter class. I've found the problem in the rails source, and am not sure the best way to proceed.
The problem occurs in ActionDispatch::Http::ParameterFilter. In the compiled_filter method, an error occurs on line 38: key = key.dup when key is a symbol, because symbols are not duplicable. Here is the source:
def compiled_filter
...
elsif blocks.present?
key = key.dup
value = value.dup if value.duplicable?
blocks.each { |b| b.call(key, value) }
end
I see that they only call dup on value when it is duplicable. If I patch the source to only call dup on key when key is duplicable, then my problem goes away. I'm assuming there is a reason why the author put that condition on value and not key, so I'm curious if someone out there has a better understanding of this code.
This error only occurs when you add a block to your filter params in application.rb. So, maybe there is a workaround for my original issue that does not require using a block here. If you're interested see my coworker's question Rails: Filter sensitive data in JSON parameter from logs
The key for which this is a problem is :action. This comes from rails and I don't know if there is any way to force it to be a string instead.
I filed a rails bug https://rails.lighthouseapp.com/projects/8994/tickets/6557-symbol-duplication-error-in-parameterfilter-compiled_filter and I have a patch ready that adds if key.duplicable? to the key.dup line, I'm looking for input on whether or not that is the right solution.
This looks like a bug in Rails. Either the key should be a string rather than a symbol, or the dup should be protected by duplicable?.
You should file a bug at https://rails.lighthouseapp.com/, including a minimal test case if possible.

Resources