Understanding ruby's "|| =" specification and what is Rails presence method?

what's this

The writer||=I wrote it as a memorandum because it was treated as a mess. I also explain the presence method (?), So please have a look if you like! If you have any suggestions, please leave them in the comments section.

In the first place "||=What is

Simply put ** self-substitution ** Same meaning as the code below that you often see in ruby

result = 1
result += 2
p result #=> 3

A version that changed this to "If nil or false, substitute the right side".

def check(arg)
  arg ||= 'nil or false'
  p arg
end
check('hoge') #=> 'hoge'
check(nil) #=> 'nil or false'
check(false) #=> 'nil or false'

||=Detailed movement of

I have a nice sample code in the Ruby docs, so I'll excerpt it

p obj.foo ||= true
p obj.foo || (obj.foo = true)

It works exactly the same as above.

||Make a comparison with.||Returns what was first true. If obj.foo is not nil or false, it returns true, that is, the left side. If the left side is false, assign the code on the right side to the variable on the left side. about it.

The trap I was addicted to (digression)

Because I couldn't understand the specification that ** nil or false is assigned to the left side ** above, Since it was a little swamped, I will leave it as a memorandum. That's also why I tried to write this article.

I was developing in Rails and wanted to create a method that meets the following requirements:

-Get a record with the specified id and boolean type from the DB -Set the boolean type of the acquired record to false and update

-Records do not always exist. -Return if records that match the conditions cannot be obtained

I wrote the following code (variable name is tentative)

def find_and_change_default(post_id)
  post = Post.find_by(id: post_id, boolean: true)
  if post.present?
    post.update(boolean: false)
  end
end

One problem I thought was "I found the post, but it's redundant to check the existence with present?" I thought.

After a lot of research, I found out about Rails' presence method and modified it as follows.

def find_and_change_default(post_id)
  post = Post.find_by(id: post_id, boolean: true).presence || return
  post.update(boolean: false)
end

The presnece method is defined in Rails as follows:

activesupport/lib/active_support/core_ext/object/blank.rb


  def presence
    self if present?
  end

If the receiver (post this time) is present? And returns true, it returns self. The Rails guide introduced the following usages.

host = config[:host].presence || 'localhost'

If there is host in config, substitute it. If not, substitute localhost. Is the code.

「||=The relationship between the presence method and

~~ I wanted to explain here the most. Until now, it's the undercard ~~

||=If the left side of is nil or false, substitute the right side. It is a tragedy that happened without understanding the specifications.

If it is nil, it will return, so||=Seems to be usable! I wondered why I wrote this code

  post = Post.find_by(id: post_id, boolean: true).presence ||= return
  #=> undefined method `presence=' for nil:NilClass (NoMethodError)

The above is the result when there is no matching record. I had a headache when I threw an error, but after checking the ruby ​​documentation 100 times, I understood. https://docs.ruby-lang.org/ja/latest/doc/spec=2foperator.html

When I looked up the usage, I found the following code in Rails (methods are appropriately extracted from Rails code)

def open_connection(server = nil)
  server ||= TestServer.new
  #Subsequent processing
end

I thought it was common to use ** to check the value taken as an argument **. In the previous case, I wanted to get the data from the DB and store it in a variable, but I didn't understand the meaning of assigning it to the left side. I have written the above code. Assigning return to the left side that is executing the nil.presence method is no longer a mess.

Recommended Posts

Understanding ruby's "|| =" specification and what is Rails presence method?
What is Ruby's self?
What is Ruby's attr_accessor?
[Rails] What is the difference between redirect and render?
What is the pluck method?
What is Rails gem devise?
[Rails] require method and permit method
Rails "render method" and "redirect method"
Rails is difficult and painful!
Rails is difficult and painful! Ⅱ
What is Microservices? And Microservices Frameworks
What is Rails Active Record?
What is the initialize method?
[Rails] What is the difference between bundle install and bundle update?
What is the difference between an action and an instance method?
[Ruby on Rails] What is Bcrypt?
What kind of method is define_method?
What is follow_redirect! Following ?: Rails Tutorial Memorandum-Chapter 7
[For programming beginners] What is a method?
What is Java and Development Environment (MAC)
What is the main method in Java?
What is RSA signature verification and why?
[Rails] What is a dot (.) Or a colon (:)?
[Ruby] What is the slice method? Let's solve the example and understand the difference from slice!
rails method
What is the difference between SimpleDateFormat and DateTimeFormatter? ??
After all, what is [rails db: migrate] doing?
[Rails] Difference between create method and new + save method