Add class for number_with_precision - ruby-on-rails

I have a code, which shows price:
def value
h.number_with_precision(object.value, precision: 2,strip_insignificant_zeros: false)
end
And i put this value in haml: %b= #{number.value}
For example: showing price "1234.02" inside <b/> and I need some styles to ".02". How to put precision inside span?
EDIT:
Ruby string have formatter built in. No need to use any class.
Just use "%.2f" % #{number.value}

You have to split number.value with '.' as separator, and use it like
full_value = number.value.to_s.split('.')
haml: %b #{full_value[0]}.
%span #{full_value[1]}

As you are not stripping insignificant zeroes you will always have 3 digits at the end you need to format (assuming you're including the decimal place).
You can do
number.value.to_s[0..-4]
Which will give you all characters in the string apart from the last 3, and then
number.value.to_s.last(3)
To return the part you want to format separately
If you don't want to format the decimal point, and just need the last 2 characters separated:
number.value.to_s[0..-3]
number.value.to_s.last(2)
You can then format these as needed

Related

Remove from a string the characters where bytesize is greater than 2 with Ruby

I have a problem with mysql and certain characters. If a user enters "hello ●", I obtain this error:
Mysql2::Error: Incorrect string value: '\\xE2\\x97\\x8F he...' for column 'subject'
I would like to exclude all characters whose bytesize is greater than two, i.e., keep French characters like é, à, ç, and remove emojis or characters like ●.
Given string = "hèllö>●!", I would like to obtain "hèllö>!". In order to do so, I wrote this:
def bytesize(var)
var.each_char do |char|
puts char.bytesize
end
end
bytesize(string)
1
2
1
1
2
1
3
1
# => "hèllö>●!"
which is not what I expected. What is the best way to remove from all characters whose the bytesize is greater than two from a string?
I don't do that in the model because I can manage this with a gem, but my problem appears when a job wants to put the string in the logs of Amazon SES.
Elaborating on OP's efforts, not using regular expressions:
string = "hèllö>●!"
cleaned = string.each_char.with_object("") do |char, str|
str << char unless char.bytesize > 2
end
p cleaned
I suspect that you are getting that error message because you have the wrong column text encoding. If you are using Unicode in your system, and this day and age you should be, your column type should be utf8mb4. See this on how to change your column types.
Taking your comment into account the following will remove any characters outside the BMP
sentence.gsub(/[\u{10000}-\u{10FFFF}]/,'')

Isolating/removing Characters from string using rails

I am using ruby on rails
I have
article.id = 509969989168Q000475601
I would like the output to be
article.id = 68Q000475601
basically want to get rid of all before it gets to 68Q
the numbers in front of the 68Q can be various length
is there a way to remove up to "68Q"
it will always be 68Q and Q is always the only Letter
is there a way to say remove all characters from 2 digits before "Q"
I'd use:
article.id[/68Q.*/]
Which will return everything from 68Q to the end of the string.
article.id.match(/68Q.+\z/)[0]
You can do this easily with the split method:
'68Q' + article.id.split('68Q')[1]
This splits the string into an array based on the delimiter you give it, then takes the second element of that array. For what it's worth though, #theTinMan's solution is far more elegant.

Converting a decimal to price format in Ruby

Hey I am using the ruby on rails framework and I have a price variable that is a decimal. Naturally values like $39.99 is fine but when the price is $39.90 my app shows the price as $39.9 How could I change that.
My view
%b price
= #product.price
rails includes the number_to_currency(#product.price) helper. Little simpler and easier to remember.
The standard answer here is to use sprintf.
sprintf("$%2.2f", #product.price)
This will format your number with a leading dollar sign, then the number to two decimal places.
If you want, you can write your custom helper method for this.
def num_to_currency price
"$#{price.to_i}."+"#{(price % 1.0)}"[2..3]
end
1.9.3 (main):0 > num_to_currency 6.90
=> "$6.90"

Show only first couple of paragraphs. Ruby on Rails

I am using simple_format(#company.description) to make a text into a number of paragraphs. On one page I only want to show, lets say, the first three paragraphs. Is there any nifty ruby method that can help out here or should I read up on my regular expression skills, which are very out of date.
Cheers Carl
The truncate helper method takes an optional :separator. Since simple_format uses <br /> tags to indicate paragraphs, you should be able to do something like this:
truncate(simple_format(#company.description), length: 3, separator: '<br />')
Personally, I'd round the text before putting it into a formatter. I'd assume you have a \r\n or \n in your text. Why format 1000 paragraphs if all you need is the first 3.
def get_first_paragraphs(text, desired = 3)
text.each_with_index do |character, index|
if(character == "\n")
desiredParCount -= 1
return text[0..index] if(desiredParCount <= 0)
end
end
return text;
end
It's a function sure, but it's the fastest method.. if speed is important. (it always is, ALWAYS!) :)

How to set Default format for activerecord fields of type string?

Here's an easy one:
How do I go about setting the default format for a string field in ActiveRecord?
I've tried the following:
def phone_number_f
"...#{phone_number}format_here..."
end
But I'd like to keep the method name the same as the field name.
Not sure exactly what you're looking for, but I'm guessing it's this.
def phone_number
"...#{read_attribute(:phone_number)}format_here..."
end
Are you looking to store things in a specific format or output them in a specific format.
Unless you have to do calculations on things it makes more sense to put data in the correct format before storing it in the database. That way you only ever need to convert it once.
The best way to do that is with a before_validate callback to put things in the proper format if it isn't already. Use it in tandem with the validates_format_of helper to ensure that it worked. You may have been passed data that cannot be massaged into the format you want.
If you do need to perform calculations and may need to change output formatting, you can use the formatter callback method as a formatting string. You may want to look into String#sub, String#unpack and Kernel#sprintf/String#%.
North American Phone number example:
The regular expression could be wrong, but that's not the important part of the example.
before_validate :fix_phone_number_format
def fix_phone_number_format
self.phone_number = "(%s) %s-%s" % phone_number.gsub(/[\D]/, "").unpack("A3A3A4")
end
validates_format_of :phone_number, :with => /^(\d{3}) \d{3}-\d{4}/
EDIT: the conversion is slightly complicated, so here's a step by step breakdown as as ruby does things. With phone number given as 123-555-1234.
"(%s) %s-%s" % phone_number.gsub(/[\D]/, "").unpack("A3A3A4")
"(%s) %s-%s" % "123-555-1234".gsub(/[\D]/, "").unpack("A3A3A4")
# remove all non digits from the string
"(%s) %s-%s" % "1235551234".unpack("A3A3A4")
# break the string up into an array of three pieces.
# Such that the first element is the first 3 characters in the string,
# the second element is 4th through 6th characters in the string,
# and the third element is the remaining digits.
"(%s) %s-%s" % ["123","555","1234"]
# Apply the format string to the array.
"(123) 555-1234"

Resources