简体   繁体   中英

ruby pass argument into inner method

I'm new to programming and I'm doing rails. Here I have a ruby question.

I have a method counterpart which take message and conversation as argument

    def counterpart(message, conversation)
        if  message.author_id == conversation.sender_id
          counterpart_id = conversation.receiver_id
        else
          counterpart_id = conversation.sender_id
        end
    end

and in below method create_notification, I want to call counterpart method within to get variable counterpart_id. But how can I pass the argument message and conversation into counterpart here?

    def create_notification(message, conversation)
        counterpart(message, conversation)
        notification = message.create_notification(
                  notifier_id: message.author_id,
                  receiver_id: counterpart_id,
                  content: "#{message.author.name} sent you a message",
                  title: "message")
    end

thanks

We don't know enough about your models. So, as far as I know, the best way to make your code works is move to

def counterpart(message, conversation)
  message.author_id == conversation.sender_id ? conversation.receiver_id : conversation.sender_id
end

def create_notification(message, conversation)
  message.create_notification(notifier_id: message.author_id,
      receiver_id: counterpart(message, conversation),
      content: "#{message.author.name} sent you a message",
      title: "message")
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM