How to get constant name by filename - ruby

Given a filename, I would like to know if there is a ruby way to obtain the constant name for it.
e.g:
"lib/myproject/connect.rb" => MyProject::Connect
p.s: I know I can create a script for this.
EDIT: consider only the first one at the top.

You may wanna take a look at the implementation of Inflector#camelize in ActiveSupport, see: http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-camelize

Related

Ruby Dropdown select based on first character

I have a dropdown of vehicle makes that I want my users to start selecting as they type. First character typed should find the first character in the makes. The problem is that it searches anywhere in the make for a character and does not start at the first character like my users would like. For example... if you type an "r" you get: Alfa Romeo, Aston Martin, Chevrolet, Chrysler, etc... well before you get a Renault.
I create my list from the database. My haml looks like this:
.field-row
= render partial:'/makes/make_select', locals:{id:'make_id'}
That calls this _make_select.html.haml
= collection_select :vehicle, id, Make.all.order(:name), :id, :name, {prompt:true}, {title:'Select Make', class:'make-select', 'data-allow-empty' => 'no'}
I cant seem to find any docs on Ruby that shows me the valid options for collection_select. Maybe there is an option that allows this?
I have read that I might need to use jQuery to accomplish this. Was just trying to figure out if there might be an easier way with just a simple option in the haml.
Let me know if there is anything else you would like to see.
thanks!
You could add logic to your controller and to check using a SQL query, something like this, depends on the database you're using.
#makes = Make.where('name LIKE ?', "#{params[character]}%")
Check out the MySql docs on pattern matching
https://dev.mysql.com/doc/refman/8.0/en/pattern-matching.html
You should not add your Model query inside a view, should add it.
In your above case, I suggest you use https://github.com/argerim/select2-rails it very powerful and already have what you need.

Is `assert_equal ... or assert_equal ...` possible in ruby minitest?

I am creating a test that can be expressed as a disjunction of assertions; when the first assertion fails, then it should look at the next. Particularly, an item will be equal to one of two things. Which one, I do not know.
My code looks something like this. It does not work but it might give you an idea of what I am trying to do.
asset_one = Cache.asset_one
asset_two = Cache.asset_two
assert_equal(asset_one.name, Pages.name) or
assert_equal(asset_two.name, Pages.name)
The Pages.name should match one of the targets. I don't know which one. If it doesn't match the first, then I want it to skip it and try to match the second.
Any help is as always much appreciated.
If you want to match any one of the object having the given name, you can use assert_includes
asset_one = Cache.asset_one
asset_two = Cache.asset_two
assert_includes([asset_one, asset_two].map(&:name), Pages.name)
This should solve your purpose.

Mockaroo Formulas for random date range using Ruby

I am trying to create a data field using Mockaroo and they say they have Ruby support but I know nothing about Ruby so I am trying to find out how to do a field that will randomly choose between the 3 options.
now() or
now()+days(-1) or
now()+days(-2) or
now()+days(-3)
Idea 1
I was initially thinking something using random like now()+days(this.rand(-3))
Idea 2
I also thought of using or logic like now() or now()+days(-3) or etc...
This answer may end up being different than a typical ruby solution since Mockaroo has their own little API to use too... Appreciate any help that can be given.
Turns out I had to use the random function first and pass in min and max date parameters.
random(now()+days(2), now()+days(-3))

Ruby and Excel Data Extraction

I am learning Ruby and trying to manipulate Excel data.
my goal:
To be able to extract email addresses from an excel file and place them in a text file one per line and add a comma to the end.
my ideas:
i think my answer lies in the use of spreadsheet and File.new.
What I am looking for is direction. I would like to hear any tips or rather hints to accomplish my goal. thanks
Please do not post exact code only looking for direction would like to figure it out myself...
thanks, karen
UPDATE::
So, regex seems to be able to find all matching strings and store them into an array. I´m having some trouble setting that up but should be able to figure it out....but for right now to get started I will extract only the column labeled "E Mail"..... the question I have now is:
`parse_csv = CSV.parse(read_csv, :headers => true)`
The default value for :skip_blanks is set to false.. I need to set it to true but nowhere can I find the correct syntax for doing so... I was assumming something like
`parse_csv = CSV.parse(read_csv, :headers => true :skip_blanks => true)`
But no.....
save your excel file as csv (comma separated value) and work with Ruby's libraries
besides spreadsheet (which can read and write), you can read Excel and other file types with with RemoteTable.
gem install remote_table
and
require 'remote_table'
t = RemoteTable.new('/path/to/file.xlsx', headers: :first_row)
when you write the CSV, as #aug2uag says, you can use ruby's standard library (no gem install required):
require 'csv'
puts [name, email].to_csv
Personally, I'd keep it as simple as possible and use a CSV.
Here is some pseudocode of how that would work:
read in your file line by line
extract your fields using regex, or cell count (depending on how consistent the email address location is), and insert into an arry
iterate through the array and write the values in the fashion you wish (to console, or file)
The code in the comment you had is a great start, however, puts will only write to console, not file. You will also need to figure out how you are going to know you are getting the email address.
Hope this helps.

how to replace a string in a ruby file after a match is found

I have a xml file, which i need to modify from my ruby script and save it. xml file looks something like
`
<mtn:messages>
<mtn:message correlation-key="0x" sequence="4">
<mtn:header>
<mtn:protocol-version>0x4</mtn:protocol-version>
<mtn:message-type>0x0F04</mtn:message-type>
<mtn:ttl>4</mtn:ttl>
<mtn:qos-class-of-service>0</mtn:qos-class-of-service>
<mtn:qos-priority>2</mtn:qos-priority>
</mtn:header>
</mtn:message>
</mtn:messages>
</mtn:test-case>
<mtn:test-case title="Train-Consist-Message">
<mtn:messages>
<mtn:message correlation-key="0x" sequence="4">
<mtn:header>
<mtn:protocol-version>0x4</mtn:protocol-version>
<mtn:message-type>0x0F04</mtn:message-type>
<mtn:ttl>4</mtn:ttl>
<mtn:qos-class-of-service>0</mtn:qos-class-of-service>
<mtn:qos-priority>2</mtn:qos-priority>
</mtn:header>
</mtn:message>
</mtn:messages>
</mtn:test-case>`
I need to replace <mtn:ttl>4</mtn:ttl> with <mtn:ttl>some other value</mtn:ttl> which comes under <mtn:test-case title="Train-Consist-Message"> and save it.
I have written below code, but its replacing all occurances of <mtn:ttl>4</mtn:ttl>.
`doc = IO.read(ENV['CadPath1']+ "conf\\cad-mtn-config.xml")
doc.gsub!(pattern, str)
File.open("File path", "w"){|fh| fh.write(doc)}`
Please help me with this. Waiting for your early reply...
String#gsub! modifies the string in-place, replacing all instances with the replacement specified. If you only want to replace the first instance, use String#sub or String.sub!.
The suggestion from Mike about using sub instead of gsub is good. But parsing XML (and HTML) with regular expression is usually frowned upon.
From your question I assume that you locate the to-be-modified element in terms of parent-child relations, not in terms of the source code order (i.e. you will not be able to say: "modify the second occurrence of this pattern"), so inventing a reliable regular expressions may be very, very hard.
You should use a parser library to find the element you want to change. There is a pretty large collection of those. See some of them at http://ruby-toolbox.com/categories/html_parsing.html and pick one, or use a built-in REXML library.
Alternatively, you could use a very simple 'html-scanner' module, which is included in Rails' ActionController (action_controller/vendor/html-scanner.rb), but if you do not use Rails, I am not sure whether extracting it is worth your time.
The exact code will depend on the parser you choose. Usually they have pretty good documentation/tutorials, so I am sure you will be able to handle it.

Resources