0

I'm kind of doubting this is possible, but I figured I'd try and see if the community can help me come up with a solution.

In my app users can create an invoice and I'm trying to allow them to set up recurring invoices from a form so they can select a number, an interval (year, month, day) and from there I'll be able to get an interval.

Ideally it'd form something like this: 1.year.from_now

which would give me the date to send the next invoice. This is a built in rails helper that I'd like to form using information from my database

So on Invoice.create I check to see if it's a recurring invoice that will be turned into a template (Recurringinvoice) and if it is I create it:

    Recurringinvoice.create(customer_id: @customer.id, company_id: @company.id, 
invoice_number: @invoice.invoice_number, private_notes: @invoice.private_notes, 
customer_notes: @invoice.customer_notes, payment_terms: @invoice.payment_terms, 
status: "unpaid", discount: @invoice.discount, po_number: @invoice.po_number, 
interval: @invoice.interval, 
invoice_interval_number: @invoice.invoice_interval_number)

What I'd like to do: @invoice.invoice_interval_number + "." + @invoice.interval + ".from_now"

That would give me 1.year.from_now, or 2.days.from_now, etc.

Is there anyway I can make this happen? Is there a better solution I'm not thinking of?

1 Answer 1

1

In ruby, you can use the send method to call a method by its name.

  • @invoice.invoice_interval_number is an Integer.
  • @invoice.interval contains the name of a method you want to call on your Integer.
  • from_now is a method you want to call on the result of the previous method.

Which gives us :

@invoice.invoice_interval_number.send(@invoice.interval).from_now

Documentation : http://ruby-doc.org/core-2.2.3/Object.html#method-i-send

Sign up to request clarification or add additional context in comments.

2 Comments

Beautiful. It works perfectly and I never knew about that.
That's part of the metaprogramming possibilities of Ruby. Which is awesome :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.