In my Rails application I have a file sample_data.rb
inside /lib/tasks
as well as a bunch of test files inside my /spec
directory.
All these files often share common functionality such as:
def random_address
[Faker::Address.street_address, Faker::Address.city].join("\n")
end
Where should I put those helper functions? Is there some sort of convention on this?
Thanks for any help!
rake extension and are placed in Rails. root/lib/tasks . You can create these custom rake tasks with the bin/rails generate task command. If your need to interact with your application models, perform database queries and so on, your task should depend on the environment task, which will load your application code.
You can get a list of Rake tasks available to you, which will often depend on your current directory, by typing rake --tasks . Each task has a description, and should help you find the thing you need.
Go to Websites & Domains and click Ruby. After gems installation you can try to run a Rake task by clicking Run rake task. In the opened dialog, you can provide some parameters and click OK - this will be equivalent to running the rake utility with the specified parameters in the command line.
Rake stands for Ruby Make. It's a standalone Ruby utility that "replaces the Unix utility 'make', and uses a Rakefile and .rake files to build up a list of tasks". Basically, it is a task runner for Ruby. Rails uses Rake Proxy to delegate some of its tasks to Rake.
Rake is a popular task runner in Ruby. What is a task? These are small tasks that without Rake would be scattered all over your project on different files. Rake centralizes access to your tasks. Rake also makes a few things easier, like finding files that match a certain pattern & that have been modified recently.
Rake stands for Ruby Make. It's a standalone Ruby utility that "replaces the Unix utility 'make', and uses a Rakefile and .rake files to build up a list of tasks". Basically, it is a task runner for Ruby.
Another Rails view helper is number_to_human. This is great when you want to take a number & print it as you would read it, which makes it feel more human. You can find more helpers in the Ruby on Rails documentation. But did you know you can write your own?
You could create a static class, with static functions. That would look something like this:
class HelperFunctions
def self.random_address
[Faker::Address.street_address, Faker::Address.city].join("\n")
end
def self.otherFunction
end
end
Then, all you would need to do is:
execute it like:
HelperFunctions::random_address(anyParametersYouMightHave)
When doing this, make sure you include any dependencies in your HelperFunctions
class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With