Best practices and code for generating booking reference number? [closed] - ruby-on-rails

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I would like to generate booking reference numbers so they can easily be communicated by voice, written down, texted etc.
I currently use uuid, which works well, but results in poor UX, as strings like 510632cc-3aa4-41c2-8bd0-cbd2bd671ef4 are difficult to communicate.
Here is an Airbnb booking reference, which is nice and short and easy to communicate verbally:
Best practices
I gave it some thought and decided on using all capital letters except O (and no lower case letters), and the numbers 1-9.
This results in 25 + 9 = 34 possible characters. There could therefore be
34^6 = 1544804416 (1.5 billion) 6-character codes
Or if that isn't enough, 34^7 = 52523350144 (52 billion) 7-character codes
In my use case 6-characters is ample.
To summarise, the booking_reference should be a random string of letters A-Z except O, and numbers 1 -9 (not 0), no lower case letters. And the column must be unique - no duplicate strings.
Question
Have I encapsulated best practices in my ideas above, and, presuming I create a booking_reference column to store the string, how can I generate these in the bookings#create controller action?
Note: I'm not sure if it's relevant to the ruby tag; please feel free to remove that tag if it isn't relevant.

You should not do this in your controller.
This example below will generate a 8-character booking reference before creating your record, no zeros and Os. Note that it doesn't look for collisions, you should elaborate on that if you expect a lot of records, there are many different ways to do it including model validations and so on. You might also want to add an index on booking_reference to your table.
class YourModel < ApplicationRecord
# ...
before_create :generate_booking_reference
def generate_booking_reference
self.booking_reference = 8.times.map { [*'1'..'9', *'a'..'n', *'p'..'w'].sample }.join
# TODO check for collisions
end
# ...
end

Related

What is the rule for multiple methods(?) on and object (i.e. num.to_s.chars.map{|x| x.to_i**2}.join.to_i)? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
What is the structural rule of something like this? I'm newer to programming and I don't know the technical term for the ".something's" (methods?).
But, in this example, there are 5 (to_s, chars, map, join, and to_i).
num.to_s.chars.map{|x| x.to_i**2}.join.to_i
Basically, all I am wondering is, what is the structure to building these? I've tried doing some similar and have received errors. So, is there a specific order or structure to these? And is the correct term method?
Ideally you should first get fundamental of ruby language. Ruby is one of the easiest language to get hold on. Checkout https://try.ruby-lang.org and you will better understand following.
It's an expression where there is chain of methods being called on the result of each expression.
Assuming num is an integer, see the comment below
num
.to_s # to_s on any ruby object converts it to string
.chars # returns individual characters in string array
.map { |x| # iterates over each number character in array
x.to_i**2 # and convert each character to integer and sqare it( ** is exponent operator)
}
.join # map returns new array and join/conctenate each number
.to_i # convert it back to integer
so if num is 123, it returns 149 which essentially each number is squared.
You can try yourself by running this code one by one in irb

When to use percent i method to create arrays with symbols? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
In Ruby there is a nifty method of creating an array of symbols.
Percent i method.
%i[a b c]
I am working in a team based environment, and although I can see this being useful with a large list of array, I have this is being implemented for everything
a = %i[] # Empty array
cancan abilities
can :manage, :all
cannot %i[create show update], AModel
cannot %i[create], BModel
cannot %i[show], CModel
Is it good to initialize all arrays using this methods or just
cannot [:create, :show, :update], AModel
I know there is no 'right' way but I would like the pros and cons to help me decide
In terms of the language itself, there are no important differences between the two, so it really comes down to a matter of preference. Personally, I think that the array of symbol literals ([:create, :show, :update]) looks more Ruby-like and that is what I'd use, but you should discuss it with your team. The most important part is being consistent, and you don't want to make the decision alone.
In the general case of when to use %i instead of writing out a literal array of symbols, I'd consider using the former if it was a list of symbols that had certain meaning, like a class constant or something, and there were more than just a couple. I've been using Ruby for a while now and until this question didn't really register the existence of %i, so it's relatively uncommonly used. It's maybe not in the average Rubyist's vocabulary, so that might be another reason to stay away from it.

Structuring data in a conversion app [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
In an application I need to convert values between metric, British imperial and US imperial, e.g. kilos to stones + pounds (UK) to pounds (US). How best to store the user-inputted data?
Is it better to convert all inputted values to e.g. metric and save as a float, or keep the user inputted data as say a literal string and interpret on each application launch?
The maths/equations etc is all good, it's more knowing what the most efficient structure is for storing values that can be represented in different ways, in a database?
It really comes down to what precision you need. Storing the value as String might be safe but is extremely inefficient. For simple 1 to 1 value conversions it might be efficient enough. For converting thousands of values it probably won't.
I would go with scalar types representing the most complex value the user is able to enter manually. Derive calculations from those original values to avoid losing complexity.
One note: since you're dealing with real world values (I presume), ditch the sign and use the unsigned variants if you're going with scalar value types.
This is the approach I use, Make an NSObject called WeightObject that have 2 propertiesL
1- the value the user entered (for example 3)
2- a unit the user used example:(KiloGrams/pounds etc..).
lastly save the object. this way yo keep the record exactly as user entred, and you make the method inside the object to return the value in KG or in punds etc...
so later you say float x = myWeightObject.KilosValue

Ruby dynamically build and assign varibles [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I am building a rails app that i need to update totals of managers each time someone is added. The method that updates the totals to me is looking really bad there is a lot of repetition going on that could be solved with a bit of metaprogramming. so i have a private method being called on before_save called update_totals
So we categorize them like this there is four races, african, coloured, indian and white there are three kinds of managements senior, middle and junior and then obviously two kinds of genders male and female. I need to be able to assign each possible variation of the three so i end up with something like this.
self.number_of_african_female_senior_managers = managers.native.african.female.senior.count
self.number_of_african_male_senior_managers = managers.native.african.male.senior.count
self.number_of_african_female_middle_managers = managers.native.african.female.middle.count
self.number_of_african_male_middle_managers = managers.native.african.male.middle.count
self.number_of_african_female_junior_managers = managers.native.african.female.junior.count
self.number_of_african_male_junior_managers = managers.native.african.male.junior.count
I would need to do this for each race. So i thought of building them dynamically and then having them assigned.
So something like this:
["african", "indian", "coloured", "white"].each do |race|
["senior","middle","junior"].each do |management_type|
["male","Female"].each do |gender|
"number_of_#{race}_#{gender}_#{management_type}_managers" = managers.native.race.gender.management_type.count
end
end
end
But this will return strings and not variables that be assigned. I saw there is a define_method method that can dynamically build methods but that looks like you have to call it outside of the constructor in this example, and i saw that you can use Object#send like this example, but i cant see that working in this situation either.
Is this a good ruby practice? Its adding a bit of complexity but removing a lot of DRY code.
Is this a good ruby practice?
DRY is a good ruby practice, so the answer to your question is: YES
Regarding your code you will probably use send in such a situation.
something like self.send("number_of_#{race}_#{gender}_#{management_type}_managers=", managers.send(native).send(race).send(gender).send(management_type).count)
This still looks pretty ugly to me. I am kind of asking myself why that datastructure is so insane. Why are you not using a simple hash structure here?

Ruby - converting a hashtag to actual word(s) ? (#contentmarketing => content marketing) [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Hashtags sometimes combine two or more words, such as:
content marketing => #contentmarketing
If I have a bunch of hashtags assigned to an article, and the word is in that article, i.e. content marketing. How can I take that hash tag, and detect the word(s) that make up the hashtag?
If the hashtag is a single word, it's trivial: simply look for that word in the article. But, what if the hash tag is two or more words? I could simply split the hashtag in all possible indices and check if the two words produced were in the article.
So for #contentmarketing, I'd check for the words:
c ontentmarketing
co ntentmarketing
con tentmarketing
...
content marketing <= THIS IS THE ANSWER!
...
However, this fails if there are three or more words in the hashtags, unless I split it recursively but that seems very inelegant.
Again, this is assuming the words in the hash tag are in the article.
You can use a regex with an optional space between each character to do this:
your_article =~ /#{hashtag.chars.to_a.join(' ?')}/
I can think of two possible solutions depending on the requirements for the hashtags:
Assuming hashtags must be made up of words and can't be non-words like "#abfgtest":
Do the test similar to your answer above but only test the first part of the string. If the test fails then add another character and try again until you have a word. Then repeat this process on the remaining string until you have found each word. So using your example it would first test:
- c
- co
- ...
- content <- Found a word, start over with rest
- m
- ma
- ...
- marketing <- Found a word, no more string so exit
If you can have garbage, then you will need to do the same thing as option 1. with an additional step. Whenever you reach the end of the string without finding a word, go back to the beginning + 1. Using the #abfgtest example, first you'd run the above function on "abfgtest", then "bfgtest", then "fgtest", etc.

Resources