Return defaul value of hash ruby - ruby

I am making a hash like this:
enum_gender={:male=>1,:female=>2, :default_when_fail=>3}
but I need that when I access
enum_gender[:somekey]
It return 3 by default or some value specified
:some_key could be any other :assd, :asf, :asdf
how do I do this ?

You can use fetch:
enum_gender={:male=>1,:female=>2}
enum_gender.fetch(key, 3)
enum_gender.fetch('a_non_key', 3) #=> 3

You can do this
enum_gender = Hash.new(3).merge({:male=>1,:female=>2})
=> {:male=>1, :female=>2}
enum_gender[:somekey]
=> 3

I suggest writing some kind of conditional. You could write it as its own function, an if/else/end block, or a ternary as you like.
Example:
if enum_gender.has_key?(key)
return enum_gender[key]
else
return <default value>
end

Related

How to set default value for Dry::Validation.Params scheme?

I have next scheme
Dry::Validation.Params do
optional(:per_page).filled(:int?, lteq?: 1000)
optional(:page).filled(:int?)
end
If I pass empty hash for validation I get empty output but I want to set default values for my data.
I tried Dry::Types.default but it does not add default values in output. That's what I tried.
Dry::Validation.Params do
optional(:per_page).filled(Dry::Types['strict.integer'].default(10), lteq?: 1000)
optional(:page).filled(:int?)
end
Is it possible to do what I want?
The Dry::Validation has not this purpose.
I recommend you to use dry-initializer on your params before pass it to the validation.
You can do something like this:
optional(:per_page).filled(Types::Integer.constructor { _1 || 10 })
Or define your own fallback strategy as here https://github.com/dry-rb/dry-types/pull/410
optional(:per_page).filled(Types::Integer.constructor { |input, type| type.(input) { 10 } })

remove `\"` from string rails 4

I have params like:
params[:id]= "\"ebfd11a9-3aa4-415a-ba72-1b6796ea1bf6\""
And i want to get expected result as below:
"ebfd11a9-3aa4-415a-ba72-1b6796ea1bf6"
How can I do this?
You can use gsub:
"\"ebfd11a9-3aa4-415a-ba72-1b6796ea1bf6\"".gsub("\"", "")
=> "ebfd11a9-3aa4-415a-ba72-1b6796ea1bf6"
Or, as #Stefan mentioned, delete:
"\"ebfd11a9-3aa4-415a-ba72-1b6796ea1bf6\"".delete("\"")
=> "ebfd11a9-3aa4-415a-ba72-1b6796ea1bf6"
If this is JSON data, which it could very well be in that format:
JSON.load(params[:id])
This handles things where there's somehow escaped strings in there, or the parameters are an array.
Just Use tr!
params[:id].tr!("\"","")
tr! will also change the main string
In case you do not want to change main string just use :
params[:id].tr("\"","")
Thanks Ilya

More concise way of writing this array inclusion / default fallback code?

I find that I've been doing this a fair enough number of times in my Rails controllers that I'm interested in finding a better way of writing it out (if possible). Essentially, I'm validating the input to a few options, and falling back on a default value if the input doesn't match any of the options.
valid_options = %w(most_active most_recent most_popular)
#my_param = valid_options.include?(params[:my_param]) ? params[:my_param] : 'most_recent'
If you use a hash instead of an array, it would be faster and cleaner. And, since your default is "most_recent", having "most_recent" in valid_options is redundant. You better remove it.
filter_options =
Hash.new("most_recent")
.merge("most_popular" => "most_popular", "most_active" => "most_active")
#my_param = filter_options[params[:my_param]]
I too would go the Hash route.
This could be imaginable:
Hash[valid_options.zip valid_options].fetch(params[:my_param], "most_recent")
A bit farfetched.
valid_options = %w(most_active most_recent most_popular)
(valid_options & [params[:my_param]]).first || 'most_recent'
How is the below:
valid_options = %w(most_active most_recent most_popular)
valid_options.detect(proc{'default_value'}){|i| i == params[:my_param] }
Another one:
valid_options = %w(most_active most_recent most_popular)
valid_options.dup.delete(params[:my_param]) { "default" }

How to encode the text into string in rails?

unit = "Nm³/hr Air"
# => "Nm³/hr Air"
unit.html_safe?
# => false
I want the result of unit.html_safe? as true for to display in the view.
Thanks in advance
Just do unit.html_safe in your view.
Calling html_safe on a String returns a new object that looks and acts like a String.
In your case, it's not returning string that why html_safe returns false.
Have a close look http://techspry.com/ruby_and_rails/html_safe-and-helpers-in-rails-3-mystery-solved/, i hope it will help you.

ruby one-liner for this possible?

Any chance the 2nd and 3rd lines can be combined in an one-liner and hopefully save one valuable?
def self.date_format
record = find_by_key('strftime')
record ? record.value : "%Y-%b-%d'
end
the above function in a Config model try to fetch a database record by a key, return a default if not found in database.
Even better if can be written in named scope. Thanks
As requested.
Nobody yet has mentioned try, which is perfect for this situation:
value = find_by_key('strftime').try(:value) || "%Y-%b-%d"
You could use:
(find_by_key('strftime').value rescue nil) || "%Y-%b-%d"
though using exceptions is not very efficient.
Does
value = find_by_key('strftime') || "%Y-%b-%d"
work for you?
Do you need to assign a "value" variable at all? If not...
def self.date_format
find_by_key('strftime') || "%Y-%b-%d"
end

Resources