Rails Select Drop Down for States? - ruby-on-rails

I was wondering if maybe there was some already built in function for rails so that it would create a select drop down list with all the U.S. states so I wouldn't have to enter it manually. I searched online but I was unable to find any. Any suggestions on what to do so I don't have to manually enter all the states?

some helper file
def us_states
[
['Alabama', 'AL'],
['Alaska', 'AK'],
['Arizona', 'AZ'],
['Arkansas', 'AR'],
['California', 'CA'],
['Colorado', 'CO'],
['Connecticut', 'CT'],
['Delaware', 'DE'],
['District of Columbia', 'DC'],
['Florida', 'FL'],
['Georgia', 'GA'],
['Hawaii', 'HI'],
['Idaho', 'ID'],
['Illinois', 'IL'],
['Indiana', 'IN'],
['Iowa', 'IA'],
['Kansas', 'KS'],
['Kentucky', 'KY'],
['Louisiana', 'LA'],
['Maine', 'ME'],
['Maryland', 'MD'],
['Massachusetts', 'MA'],
['Michigan', 'MI'],
['Minnesota', 'MN'],
['Mississippi', 'MS'],
['Missouri', 'MO'],
['Montana', 'MT'],
['Nebraska', 'NE'],
['Nevada', 'NV'],
['New Hampshire', 'NH'],
['New Jersey', 'NJ'],
['New Mexico', 'NM'],
['New York', 'NY'],
['North Carolina', 'NC'],
['North Dakota', 'ND'],
['Ohio', 'OH'],
['Oklahoma', 'OK'],
['Oregon', 'OR'],
['Pennsylvania', 'PA'],
['Puerto Rico', 'PR'],
['Rhode Island', 'RI'],
['South Carolina', 'SC'],
['South Dakota', 'SD'],
['Tennessee', 'TN'],
['Texas', 'TX'],
['Utah', 'UT'],
['Vermont', 'VT'],
['Virginia', 'VA'],
['Washington', 'WA'],
['West Virginia', 'WV'],
['Wisconsin', 'WI'],
['Wyoming', 'WY']
]
end
in some form
<%= select_tag :state, options_for_select(us_states) %>

Thanks Codeglot. In case anyone is wanting to display the 2-letter state abbreviation instead of the full name:
def us_states
[
['AK', 'AK'],
['AL', 'AL'],
['AR', 'AR'],
['AZ', 'AZ'],
['CA', 'CA'],
['CO', 'CO'],
['CT', 'CT'],
['DC', 'DC'],
['DE', 'DE'],
['FL', 'FL'],
['GA', 'GA'],
['HI', 'HI'],
['IA', 'IA'],
['ID', 'ID'],
['IL', 'IL'],
['IN', 'IN'],
['KS', 'KS'],
['KY', 'KY'],
['LA', 'LA'],
['MA', 'MA'],
['MD', 'MD'],
['ME', 'ME'],
['MI', 'MI'],
['MN', 'MN'],
['MO', 'MO'],
['MS', 'MS'],
['MT', 'MT'],
['NC', 'NC'],
['ND', 'ND'],
['NE', 'NE'],
['NH', 'NH'],
['NJ', 'NJ'],
['NM', 'NM'],
['NV', 'NV'],
['NY', 'NY'],
['OH', 'OH'],
['OK', 'OK'],
['OR', 'OR'],
['PA', 'PA'],
['RI', 'RI'],
['SC', 'SC'],
['SD', 'SD'],
['TN', 'TN'],
['TX', 'TX'],
['UT', 'UT'],
['VA', 'VA'],
['VT', 'VT'],
['WA', 'WA'],
['WI', 'WI'],
['WV', 'WV'],
['WY', 'WY']
]
end

For this I typically use the Carmen and Carmen-Rails gems.
https://github.com/jim/carmen
https://github.com/jim/carmen-rails
Since my projects are still all on Ruby 1.8, I have to use the specific ruby-18 branch, so I have the following in my Gemfile:
gem 'carmen', :git => 'git://github.com/jim/carmen.git', :tag => 'ruby-18'
gem 'carmen-rails', :git => 'git://github.com/jim/carmen-rails.git'
Then, to create the select tag for all US states in a form where you're editing the :state_code field of an :address model object...
subregion_select(:address, :state_code, Carmen::Country.coded('US'))

This is a more detailed walkthrough. I'm using Rails 4:
Under the helpers folder I created states_helper.rb
Inside states_helper.rb:
module StatesHelper
def us_states
[
['Alabama', 'AL'],
['Alaska', 'AK'],
['Arizona', 'AZ'],
['Arkansas', 'AR'],
['California', 'CA'],
['Colorado', 'CO'],
['Connecticut', 'CT'],
['Delaware', 'DE'],
['District of Columbia', 'DC'],
['Florida', 'FL'],
['Georgia', 'GA'],
['Hawaii', 'HI'],
['Idaho', 'ID'],
['Illinois', 'IL'],
['Indiana', 'IN'],
['Iowa', 'IA'],
['Kansas', 'KS'],
['Kentucky', 'KY'],
['Louisiana', 'LA'],
['Maine', 'ME'],
['Maryland', 'MD'],
['Massachusetts', 'MA'],
['Michigan', 'MI'],
['Minnesota', 'MN'],
['Mississippi', 'MS'],
['Missouri', 'MO'],
['Montana', 'MT'],
['Nebraska', 'NE'],
['Nevada', 'NV'],
['New Hampshire', 'NH'],
['New Jersey', 'NJ'],
['New Mexico', 'NM'],
['New York', 'NY'],
['North Carolina', 'NC'],
['North Dakota', 'ND'],
['Ohio', 'OH'],
['Oklahoma', 'OK'],
['Oregon', 'OR'],
['Pennsylvania', 'PA'],
['Puerto Rico', 'PR'],
['Rhode Island', 'RI'],
['South Carolina', 'SC'],
['South Dakota', 'SD'],
['Tennessee', 'TN'],
['Texas', 'TX'],
['Utah', 'UT'],
['Vermont', 'VT'],
['Virginia', 'VA'],
['Washington', 'WA'],
['West Virginia', 'WV'],
['Wisconsin', 'WI'],
['Wyoming', 'WY']
]
end
end
Under config -> environments I put the following inside development.rb and production.rb
config.action_controller.include_all_helpers = true
Finally, inside my view I put (this is typed out in Slim HTML)
= form_for :order_submissions, url: order_url, html: { id: "order_form"} do |f|
fieldset
.form-group
= f.select(:state, options_for_select(us_states, "CA"))
The "CA" pre-selects California in the dropdown menu on load.
NOTE: I did NOT use select_tag. Using it gave me an undefined method error for select_tag (select_tag is in the Ruby guides, how can it be undefined?) Using just select made it work.

I found a problem with using a helper to contain the states. It works perfectly when creating a new record but if I want to edit an existing record I want the state in the database to be preselected in the dropdown box. I couldn't get that to work using the helper. But it does work if you create a simple states table. Here's what worked for me:
Create a states table for the select box options
Generate a State model file and database table that only has columns for state_code and state_name (or whatever you want to call them).
rails g model State state_code:string:uniq state_name:string --no-timestamps --no-test-framework. This will generate a migration file in the db/migrate folder. If you don't want an id column you can edit it by inserting , id: false into the create_table block declaration.
# db/migrate/timestamp_create_states.rb
class CreateStates < ActiveRecord::Migration
def change
create_table :states, id: false do |t|
t.string :state_code, null: false
t.string :state_name
end
add_index :states, :state_code, unique: true
end
end
And migrate the database rake db:migrate.
You can populate the table using the seed file. Make sure to delete or comment out any previously loaded data in the seed file so you don't add duplicates.
#db/seeds.rb
states = State.create!([
{ state_name: 'Alaska', state_code: 'AK' },
{ state_name: 'Alabama', state_code: 'AL' },
{ state_name: 'Arkansas', state_code: 'AR' },
{ state_name: 'Arizona', state_code: 'AZ' },
{ state_name: 'California', state_code: 'CA' },
{ state_name: 'Colorado', state_code: 'CO' },
{ state_name: 'Connecticut', state_code: 'CT' },
{ state_name: 'District of Columbia', state_code: 'DC' },
{ state_name: 'Delaware', state_code: 'DE' },
{ state_name: 'Florida', state_code: 'FL' },
{ state_name: 'Georgia', state_code: 'GA' },
{ state_name: 'Hawaii', state_code: 'HI' },
{ state_name: 'Iowa', state_code: 'IA' },
{ state_name: 'Idaho', state_code: 'ID' },
{ state_name: 'Illinois', state_code: 'IL' },
{ state_name: 'Indiana', state_code: 'IN' },
{ state_name: 'Kansas', state_code: 'KS' },
{ state_name: 'Kentucky', state_code: 'KY' },
{ state_name: 'Louisiana', state_code: 'LA' },
{ state_name: 'Massachusetts', state_code: 'MA' },
{ state_name: 'Maryland', state_code: 'MD' },
{ state_name: 'Maine', state_code: 'ME' },
{ state_name: 'Michigan', state_code: 'MI' },
{ state_name: 'Minnesota', state_code: 'MN' },
{ state_name: 'Missouri', state_code: 'MO' },
{ state_name: 'Mississippi', state_code: 'MS' },
{ state_name: 'Montana', state_code: 'MT' },
{ state_name: 'North Carolina', state_code: 'NC' },
{ state_name: 'North Dakota', state_code: 'ND' },
{ state_name: 'Nebraska', state_code: 'NE' },
{ state_name: 'New Hampshire', state_code: 'NH' },
{ state_name: 'New Jersey', state_code: 'NJ' },
{ state_name: 'New Mexico', state_code: 'NM' },
{ state_name: 'Nevada', state_code: 'NV' },
{ state_name: 'New York', state_code: 'NY' },
{ state_name: 'Ohio', state_code: 'OH' },
{ state_name: 'Oklahoma', state_code: 'OK' },
{ state_name: 'Oregon', state_code: 'OR' },
{ state_name: 'Pennsylvania', state_code: 'PA' },
{ state_name: 'Puerto Rico', state_code: 'PR' },
{ state_name: 'Rhode Island', state_code: 'RI' },
{ state_name: 'South Carolina', state_code: 'SC' },
{ state_name: 'South Dakota', state_code: 'SD' },
{ state_name: 'Tennessee', state_code: 'TN' },
{ state_name: 'Texas', state_code: 'TX' },
{ state_name: 'Utah', state_code: 'UT' },
{ state_name: 'Virginia', state_code: 'VA' },
{ state_name: 'Vermont', state_code: 'VT' },
{ state_name: 'Washington', state_code: 'WA' },
{ state_name: 'Wisconsin', state_code: 'WI' },
{ state_name: 'West Virginia', state_code: 'WV' },
{ state_name: 'Wyoming', state_code: 'WY' }
])
Then run the rake task to seed the db rake db:seed
In your form you can add this as your select box (I'm using state_code as the field name but you can make it just state or whatever you want):
<%= f.label :state_code, 'State', class: 'control-label' %>
<%= f.collection_select(:state_code, State.select(:state_name, :state_code),
:state_code, :state_name, {selected: 'CA'}, {class: 'form-control'}) %>
The collection_select helper method format in a Rails form block is f.collection_select(method, collection, value_method, text_method, options = {}, html_options = {}). If you want state_code as both the text and value of the dropdown box then change the :state_name to :state_code in the first select argument and in the text_method (note the text and value orders are reversed). In the options I preselected 'CA', but only do that for a new form not edit (or it will override the value with CA each time). You can change that to a blank {include_blank: true} or add a prompt {prompt: 'Select State'} or just have it default to the selected or first value with an empty hash {}. If you want to make the field required you can add that to the html options {class: 'form-control', required: true}
Now in your form you can populate it from the states table and it will preselect the value when editing a record.

To get this to work with simple_form, I did this.
Added this to my user.rb model:
STATES =
[
['Alabama', 'AL'],
['Alaska', 'AK'],
['Arizona', 'AZ'],
['Arkansas', 'AR'],
['California', 'CA'],
['Colorado', 'CO'],
['Connecticut', 'CT'],
['Delaware', 'DE'],
['District of Columbia', 'DC'],
['Florida', 'FL'],
['Georgia', 'GA'],
['Hawaii', 'HI'],
['Idaho', 'ID'],
['Illinois', 'IL'],
['Indiana', 'IN'],
['Iowa', 'IA'],
['Kansas', 'KS'],
['Kentucky', 'KY'],
['Louisiana', 'LA'],
['Maine', 'ME'],
['Maryland', 'MD'],
['Massachusetts', 'MA'],
['Michigan', 'MI'],
['Minnesota', 'MN'],
['Mississippi', 'MS'],
['Missouri', 'MO'],
['Montana', 'MT'],
['Nebraska', 'NE'],
['Nevada', 'NV'],
['New Hampshire', 'NH'],
['New Jersey', 'NJ'],
['New Mexico', 'NM'],
['New York', 'NY'],
['North Carolina', 'NC'],
['North Dakota', 'ND'],
['Ohio', 'OH'],
['Oklahoma', 'OK'],
['Oregon', 'OR'],
['Pennsylvania', 'PA'],
['Puerto Rico', 'PR'],
['Rhode Island', 'RI'],
['South Carolina', 'SC'],
['South Dakota', 'SD'],
['Tennessee', 'TN'],
['Texas', 'TX'],
['Utah', 'UT'],
['Vermont', 'VT'],
['Virginia', 'VA'],
['Washington', 'WA'],
['West Virginia', 'WV'],
['Wisconsin', 'WI'],
['Wyoming', 'WY']
]
Made the simple_form in my view use that:
<%= simple_form_for(#user) do |f| %>
<%= f.input :state, as: :select, collection: User::STATES %>
<%= f.button :submit %>
<% end %>

In case this one doesn't work:
<%= select_tag :state, us_states%>
Try this :
<%=select_tag 'State', options_for_select(us_states),:name=>"state",:id=>"state"%>

You have a gem that can help you: the countries gem which integrates with country_select, so you have a complete solution for states input.
Also if you want to reduce the gem dependency list you can just do:
<%= f.select :country_code, ::ISO3166::Country.all_names_with_codes,{ include_blank: true } %>

Check this https://rubygems.org/gems/country_state_select
Country State Select is a library that provides an easy API to generate Country , State / Province and City dropdowns for use in forms.
When implemented correctly, a State / Province dropdown is filled with appropriate regions based upon what Country a user has selected .
For instance, if a user chooses "United States of America" for a Country dropdown, the State dropdown will be filled with the 50 appropriate states plus the District of Columbia also then user can list city according to state selection but currently cities are limited.

Use a hash. I put mine in config/initializers/us_states.rb, but it works in a helper or just about anywhere else you prefer:
US_STATES = {
'AL': 'Alabama',
'AK': 'Alaska',
'AZ': 'Arizona',
'AR': 'Arkansas',
'CA': 'California',
'CO': 'Colorado',
'CT': 'Connecticut',
'DE': 'Delaware',
'DC': 'District of Columbia',
'FL': 'Florida',
'GA': 'Georgia',
'HI': 'Hawaii',
'ID': 'Idaho',
'IL': 'Illinois',
'IN': 'Indiana',
'IA': 'Iowa',
'KS': 'Kansas',
'KY': 'Kentucky',
'LA': 'Louisiana',
'ME': 'Maine',
'MD': 'Maryland',
'MA': 'Massachusetts',
'MI': 'Michigan',
'MN': 'Minnesota',
'MS': 'Mississippi',
'MO': 'Missouri',
'MT': 'Montana',
'NE': 'Nebraska',
'NV': 'Nevada',
'NH': 'New Hampshire',
'NJ': 'New Jersey',
'NM': 'New Mexico',
'NY': 'New York',
'NC': 'North Carolina',
'ND': 'North Dakota',
'OH': 'Ohio',
'OK': 'Oklahoma',
'OR': 'Oregon',
'PA': 'Pennsylvania',
'PR': 'Puerto Rico',
'RI': 'Rhode Island',
'SC': 'South Carolina',
'SD': 'South Dakota',
'TN': 'Tennessee',
'TX': 'Texas',
'UT': 'Utah',
'VT': 'Vermont',
'VA': 'Virginia',
'WA': 'Washington',
'WV': 'West Virginia',
'WI': 'Wisconsin',
'WY': 'Wyoming'
}
Then, in my form:
<%= form.select :state, US_STATES.invert.sort %>
Since the two-letter code is what's stored, if I want to display the name of the state, I just reference the two-letter key in the hash:
<%= US_STATES[state] %>
If you want to get really slick, initialize them in a locale file (e.g., config/locales/en.yml):
---
en:
us_states:
AL: Alabama
AK: Alaska
AZ: Arizona
# etc.
And access them in your views with:
<%= t "us_states.#{state}" %>
ℹ️ This actually works better with country and language codes when you support multiple languages in your app.

I don't know if there is something built-in Rails to make a HTML select field filled with U.S.A. states.
But here you have a screencast which explains this:
http://railscasts.com/episodes/88-dynamic-select-menus
I hope it will be useful.

I have created a sample project with detailed instructions on how to create drop-downs in Rails 4.2.2 and Ruby 2.2.2 https://rubyplus.com/articles/2501

if you want to save state on full name
# frozen_string_literal: true
module StateHelper
def us_states
[
['Alabama'],
['Alaska'],
['Arizona'],
['Arkansas'],
['California'],
['Colorado'],
['Connecticut'],
['Delaware'],
['District of Columbia'],
['Florida'],
['Georgia'],
['Hawaii'],
['Idaho'],
['Illinois'],
['Indiana'],
['Iowa'],
['Kansas'],
['Kentucky'],
['Louisiana'],
['Maine'],
['Maryland'],
['Massachusetts'],
['Michigan'],
['Minnesota'],
['Mississippi'],
['Missouri'],
['Montana'],
['Nebraska'],
['Nevada'],
['New Hampshire'],
['New Jersey'],
['New Mexico'],
['New York'],
['North Carolina'],
['North Dakota'],
['Ohio'],
['Oklahoma'],
['Oregon'],
['Pennsylvania'],
['Puerto Rico'],
['Rhode Island'],
['South Carolina'],
['South Dakota'],
['Tennessee'],
['Texas'],
['Utah'],
['Vermont'],
['Virginia'],
['Washington'],
['West Virginia'],
['Wisconsin'],
['Wyoming']
]
end
end
And then in form
<%= f.select :state, options_for_select(us_states), class:"form-control", required: true %>

Related

How to pass the phone number from Intl-Tel-Input to an input on Ruby-on-rails?

I have a simple_form with a phone number. I'm using Intl-Tel-Input to get the entire phone_number and confirm SMS in different countries (twilio). In console.log, I succeed to display the entire number. When I submit, I just get the phone_number without the country indicator (dial_code)
I read the doc, tried to get it by other way (.value, .data, etc...), but impossible to save the entire phone_number (for example, +33612345678, I just get 61234567).
Here's my code :
<div class="userphonenumber">
<%= f.input :phone_number, label: 'N° de téléphone', required: true, autofocus: true ,
input_html: { autocomplete: "intlNumber" }, wrapper_html: { id: 'userphonenumber' }%>
</div>
<script>
$("#user_phone_number").intlTelInput({
formatOnInit: true,
separateDialCode: true,
onlyCountries: ['fr', 'at', 'be', 'bg', 'cz', 'dk', 'de', 'ee', 'ie', 'el', 'es', 'hr', 'it', 'cy', 'lv', 'lt', 'lu', 'hu', 'mt', 'nl', 'pl', 'pt', 'ro', 'si', 'sk', 'fi', 'se', 'uk'],
initialCountry: "fr"
});
const flag = document.querySelector(".flag-container")
flag.addEventListener("click", () => {
var intlNumber = $("#user_phone_number").intlTelInput("getNumber");
console.log("intlNumber", intlNumber)
var input = document.querySelector("#user_phone_number");
window.intlTelInput(input);
});
</script>
I'm expecting to get +33612345678 to use the phone_number with twilio. Beginner on RoR and JS. Did I miss something ?
Thanks for your help.
Finally fix with this solution :
<script>
$("#user_phone_number").intlTelInput({
formatOnInit: true,
separateDialCode: true,
onlyCountries: ['at', 'be', 'bg', 'cz', 'dk', 'de', 'ee', 'ie', 'el', 'es', 'fr', 'hr', 'it', 'cy', 'lv', 'lt', 'lu', 'hu', 'mt', 'nl', 'pl', 'pt', 'ro', 'si', 'sk', 'fi', 'se', 'uk'],
initialCountry: "fr",
});
var phone = document.getElementById('user_phone_number')
phone.addEventListener('keyup', (event) => {
console.log(event)
});
$("form").submit(function() {
$('#user_phone_number').val($(phone).intlTelInput("getNumber"));
});
</script>
$(".form").submit( function(eventObj) {
$("<input />").attr("type", "hidden")
.attr("name", "ccode")
.attr("value", $(this).find(".selected-dial-code").text())
.appendTo(".form");
return true;
});

Associations Grails/Gorm

I have the the domain classes Rep and Bill. Bill has two fields of the type Rep called sponsor and cosponsor. I have set up the association in Bill as static hasMany = [sponsor: Rep, cosponsor: Rep]. When ever I try to save I get NULL not allowed for column "BILL_SPONSOR_ID"; SQL statement: insert into bill_rep (bill_cosponsor_id, rep_id) values (?, ?) [23502-193]. I understand that for some reason the the correct ids are not getting inserted. I have tried set both sponsor and cosponsor to nullable but I have not been able to get around it. Any idea as to what I am doing wrong?
class Bill {
String billPre
String number
String billName
Integer dateIntro
String summary
static hasMany = [cosponsor: Rep, sponsor: Rep, committee: Committee]
static constraints = {
cosponsor nullable: true
sponsor nullable: true
}
String toString() {
billName
}
}
class Rep {
String name
String party
String congress
Integer district
String state
String repEmail
String street
String phone
Integer congStart
Integer congEnd
Integer congNumStart
Integer congNumEnd
static constraints = {
name()
party()
district()
congress inList: ["House", "Senate"]
state inList: ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming']
party inList: ["Republican", "Democrat"]
repEmail email: true
street()
phone()
congStart()
congEnd()
congNumStart()
congNumEnd()
}
String toString() {
name
}
}

Twitter's typeahead

I am trying to add twitter's typeahead plugin to my rails application. I have downloaded the typeahead.bundle.js and placed it in vendor/assets/javascripts directory. And I have added //= require typeahead.bundle to app/assets/javascripts/application.js. Then I put the first example given there
<div id="the-basics">
<input class="typeahead" type="text" placeholder="States of USA">
</div>
on one of my views and the following javascript on
app/assets/javascripts/example.js
but nothing happens when i try to type characters, not even on the logs. Thanks for your help
var substringMatcher = function(strs) {
return function findMatches(q, cb) {
var matches, substrRegex;
matches = [];
substrRegex = new RegExp(q, 'i');
$.each(strs, function(i, str) {
if (substrRegex.test(str)) {
matches.push({ value: str });
}
});
cb(matches);
};
};
var states = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California',
'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii',
'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana',
'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota',
'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire',
'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota',
'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island',
'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont',
'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming'
];
$('#the-basics .typeahead').typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
name: 'states',
displayKey: 'value',
source: substringMatcher(states)
});

Dictionary-based NLTK tagger

I want to tag location string in text using NLTK and also in Stanford-NLP
and am looking for dictionary lookup tagger for NLTK/Stanford-NLP, for so far I haven't found anything with Dictionary-lookup method.
One way is to use RegexpTagger(NLTK) and supply every location strings in there, but it might slow.
I don't need to do any semantic analysis, other than to tag the locations based on my location-dictionary.
Ideas ?
You could use UnigramTagger:
#!/usr/bin/env python2
from nltk.tag.sequential import UnigramTagger
from nltk.tokenize import word_tokenize, sent_tokenize
text = 'I visited Paris and Bordeaux. Not Los Angeles'
locations = [[('Paris', 'LOC'), ('Bordeaux', 'LOC'), ('France', 'LOC'),
('Los Angeles', 'LOC')]]
location_tagger = UnigramTagger(locations)
for sentence in sent_tokenize(text):
tokens = word_tokenize(sentence)
print(location_tagger.tag(tokens))
Prints:
[('I', None), ('visited', None), ('Paris', 'LOC'), ('and', None),
('Bordeaux', 'LOC'), (',', None), ('but', None), ('not', None),
('Los', None), ('Angeles', None)]
You will need a better tokenizer if you want to tag multi-word locations like Los Angeles.
If all you need is to look up from dictionaries, then htql.RegEx() may be a good fit. Here is the example from http://htql.net:
import htql;
address = '88-21 64th st , Rego Park , New York 11374'
states=['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut',
'Delaware', 'District Of Columbia', 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana',
'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan',
'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire',
'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma',
'Oregon', 'PALAU', 'Pennsylvania', 'PUERTO RICO', 'Rhode Island', 'South Carolina', 'South Dakota',
'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin',
'Wyoming'];
a=htql.RegEx();
a.setNameSet('states', states);
state_zip1=a.reSearchStr(address, "&[s:states][,\s]+\d{5}", case=False)[0];
# state_zip1 = 'New York 11374'
state_zip2=a.reSearchList(address.split(), r"&[ws:states]<,>?<\d{5}>", case=False)[0];
# state_zip2 = ['New', 'York', '11374']
You can use parameter: useindex=True to return matching positions.

Preparing data for graph

I would like some help in order to prepare my data gathered from the database for charting.
I have a Browser model where I store all the data.
From each model I want to select the name attribute, I will put a color according an integer attribute in the model (for example if integer is 1, color => "#4572A7") and the y attribute from the model.
Can someone provide an example of the most efficient way to achieve this data format?
Final format of the data:
[
{
:name=> 'Firefox',
:y=> 1,
:color => "#4572A7"
},
{
:name=> 'IE',
:y=> 1,
:color => "#AA4643"
},
{
:name=> 'Chrome',
:y=> 1,
:color => "#89A54E"
},
{
:name=> 'Safari',
:y=> 1,
:color => "#80699B"
},
{
:name=> 'Opera',
:y=> 1,
:color => "#3D96AE"
},
{
:name=> 'Others',
:y=> 1,
:color => "#DB843D"
}
]
You could have a method that does the number-to-color translation and have something like
#browsers.to_json(methods: [:the_method_that_translates_numbers_to_colors], only: [:name, :y])
Hope that helps,
NHI

Resources