Where can I store site-wide variables in Rails 4?
The simplest, basic and default way is to use the Rails.application.config
store.
Rails.application.config.my_config = 'foo'
You can assign a config in your environment:
# application.rb
module MyApp
class Application < Rails::Application
config.my_config = 'foo'
end
end
and read it with
Rails.application.config.my_config
# => 'foo'
This approach works well for very simple applications, but if you want something more advanced there are several gems available.
I'm currently using SimpleConfig
. The main advantages are:
- per-environment configuration. You can configure default configurations for the application, then override defaults with environment specific configurations
local.rb
file for custom overridescapistrano
-like configuration style- it works nicely with the
dotenv
gem, very useful to avoid storing sensitive credentials in your repo.
Where store or implement global variables ($) in Rails?
Rails does it that way:
https://guides.rubyonrails.org/configuring.html#custom-configuration
In config/environments/production.rb
:
config.myGlobalVariable = 'blabla1'
In config/environments/development.rb
:
config.myGlobalVariable = 'blabla2'
then use this Anywhere:
Rails.configuration.myGlobalVariable
Permanent variable in Rails
Ok, so here's what I did. Instead of just putting the value to an initializer, I've made there a simple class that handles it. The variable itself is stored in a predefined file. Besides of reading the file upon the initialization, the class updates file when the value is changed, and also re-read the file periodically to maintain consistency across workers. I've also put there some basic JSON handling and backup functionality to make life easier.
For anyone interested, here's the important code:
class Pomegranate
def initialize
@delay = 30.minutes
@path = "db/pomegranate.json"
@valid = Time.now - 1
validate
end
def get(*p)
validate
p.inject(@data) {|object,key| object[key] if object}
end
def set(*p, q, v)
hash = p.inject(@data) {|object,key| object[key]||={}}
hash[q] = v
end
def save
@valid = Time.now + @delay
File.open(@path,"w") {|f| f.write(@data.to_json)}
end
private
def validate
if @valid < Time.now
@data = ActiveSupport::JSON.decode(File.read(@path)) rescue {}
@valid = Time.now + @delay
@valid = Time.now - 1 if @data.empty?
end
end
end
$pom = Pomegranate.new
Global mutable variable in Ruby on Rails 5
This can be an answer for you:
- Create a model for site information probably you already have.
- Add two fields called
targe
andprogress
. - If you calculate progress programatically then no need to add field.
- Then make view where they can update target and progress and write logic to update that field only.
Programmatically there is not a good idea other than this. I think.
Ruby on Rails - Global Variable?
A global variable doesn't fit your need. It doesn't spread across all the Ruby processes. If your web server spawns 5 ruby processes to handle 5 request at the same time, the variable defined in the first process won't be visible to the others.
There are other solutions available. You can use a database and store the flag/information on the database. Otherwise, you can use a file and store the value in the file.
The best solution would be an in-memory shared data source, such as memcached or Redis.
safe and performing way to save site wide variable
It depends whether it has to be perfectly accurate. Assuming not, you can store it in memcached and sync to the database occasionally. If memcached crashes, it expires (shouldn't happen if configured properly), you have to shutdown, etc., reload it from the database on startup.
You could also look at membase. I haven't tried it, but to simplify, it's a distributed memcached server that automatically persists to disk.
For better performance and accuracy, you could look at a sharded approach.
Setting a site-wide variable for text-field max length - Rails
Create an entry in config/application.rb
:
config.header_max_length = 50
And use this while creating forms:
<%= f.text_field :title, nil, maxlength: Rails.application.config.header_max_length %>
To make it more DRY you could create a helper method for a custom text_field_with_maxlength
or create a custom FormBuilder.
Related Topics
Ruby To_JSON Issue with Error "Illegal/Malformed Utf-8"
Rails: Opposite of Hash#To_Param
Rails How to Update a Column After Saving
How to Test Code Coverage for Rails Erb Templates
How to Chop a String into Chunks of a Given Length in Ruby
Access Instance Variable from Outside the Class
One Liner in Ruby for Displaying a Prompt, Getting Input, and Assigning to a Variable
Render an Erb Template with Values from a Hash
Convert an Array of Integers into an Array of Strings in Ruby
How to Set an Option as Selected Using Selenium Webdriver (Selenium 2.0) Client in Ruby
How to Install Nokogiri Ruby Gem with Mkmf.Log Saying Libiconv Not Found
How to Catch Errno::Econnreset Class in "Case When"
Ruby/Sinatra - Serving Up CSS, JavaScript, or Image Files
How to Get a Date from a Week Number