The text file has hundreds of these entries (format is MT940 bank statement)
{1:F01AHHBCH110XXX0000000000}{2:I940X N2}{3:{108:XBS/091502}}{4:
:20:XBS/091202/0001
:25:5887/507004-50
:28C:140/1
:60F:C0914CHF7789,
:61:0912021202D36,80NTRFNONREF//0887-1202-29-941
04392579-0 LUTHY + xxx, ZUR
:86:6034?60LUTHY + xxxx, ZUR vom 01.12.09 um 16:28 Karten-Nr. 2232
2579-0
:62F:C091202CHF52,2
:64:C091302CHF52,2
-}
This should go into an Array of Hashes like
[{"1"=>"F01AHHBCH110XXX0000000000"},
"2"=>"I940X N2",
3 => {108=>"XBS/091502"}
etc.
} ]
I tried it with tree top, but it seemed not to be the right way, because it's more for something you want to do calculations on, and I just want the information.
grammar Mt940
rule document
part1:string spaces [:|/] spaces part2:document
{
def eval(env={})
return part1.eval, part2.eval
end
}
/ string
/ '{' spaces document spaces '}' spaces
{
def eval(env={})
return [document.eval]
end
}
end
end
I also tried with a regular expression
matches = str.scan(/\A[{]?([0-9]+)[:]?([^}]*)[}]?\Z/i)
but it's difficult with recursion ...
How can I solve this problem?
I've been reading similar questions, but many of the answers are outdated or not clear enough for me.
I'd like to be able to just do something like (in a controller action):
respond_to do |format|
format.html
format.csv
end
I know I'd then need a view such as action.csv.erb
So my questions are:
1) What do I need to configure in rails to allow this to happen in general.
2) How should I setup the CSV view to display some basic fields from a model?
I have a string in Rails, e.g. "This is a Twitter message. #books War & Peace by Leo Tolstoy. I love this book!", and I want to parse the text and extract only certain phrases, like "War & Peace by Leo Tolstoy".
Is this a matter of using Regex and lifting the text between "#books" to "."?
What if there's no structure to the message, like:
"This is a Twitter message #books War & Peace by Leo Tolstoy I love this book!" or
"This is a Twitter message. I love the book War & Peace by Leo Tolstoy #books"
How can I reliably pull the phrase "War & Peace by Leo Tolstoy" without knowing the phrase ex ante.
Are there any gems, methods, etc. that can help me do this?
At the very least, what would you call what I'm trying to do? It will help me search for a solution on Google. I've tried a few searches on "parsing" with no luck.
I'm building an email system that stores my different emails in the database and calls the appropriate "deliver_" method via method_missing (since I can't explicitly declare methods since they're user-generated).
My problem is that my rails app still tries to render the template for whatever the generated email is, though those templates don't exist. I want to force all emails to use the same template (views/test_email.html.haml), which will be setup to draw their formatting from my database records.
How can I accomplish this? I tried adding render :template => 'test_email' in the test_email method in emailer_controller with no luck.
models/emailer.rb:
class Emailer < ActionMailer::Base
def method_missing(method, *args)
# not been implemented yet
logger.info "method missing was called!!"
end
end
controller/emailer_controller.rb:
class EmailerController < ApplicationController
def test_email
@email = Email.find(params[:id])
Emailer.send("deliver_#{@email.name}")
end
end
views/emails/index.html.haml:
%h1 Listing emails
%table{ :cellspacing => 0 }
%tr
%th Name
%th Subject
- @emails.each do |email|
%tr
%td=h email.name
%td=h email.subject
%td= link_to 'Show', email
%td= link_to 'Edit', edit_email_path(email)
%td= link_to 'Send Test Message', :controller => 'emailer', :action => 'test_email', :params => { :id => email.id }
%td= link_to 'Destroy', email, :confirm => 'Are you sure?', :method => :delete
%p= link_to 'New email', new_email_path
Error I'm getting with the above:
Template is missing
Missing template
emailer/name_of_email_in_database.erb in view
path app/views
Songs on Rap Genius have paths like /lyrics/The-notorious-b-i-g-ft-mase-and-puff-daddy/Mo-money-mo-problems which are defined in routes.rb as:
map.song '/lyrics/:artist_slug/:title_slug', :controller => 'songs', :action => 'show'
When I want to generate such a path, I use song_url(:title_slug => song.title_slug, :artist_slug => song.artist_slug). However, I'd much prefer to be able to type song_url(some_song). Is there a way I can make this happen besides defining a helper like:
def x_song_path(song)
song_path(:title_slug => song.title_slug, :artist_slug => song.artist_slug)
end
I'm trying to do something like the following:
@special_attributes = Model.new.methods.select # a special subset
@special_attributes.each do |attribute|
context "A model with #{attribute}"
setup do
@model = Model.new
end
should "have some special characteristic"
assert @model.method(attribute).call
end
end
end
However, @special_attributes is out of scope when running the unit tests, leaving me with a nil object on line 2. I can't figure out where to define it to bring it in scope. Any thoughts?
I am getting Encoding::UndefinedConversionError at /find/Wroclaw
"\xC5" from ASCII-8BIT to UTF-8
For some mysterious reason sinatra is passing the string as ASCII instead of UTF-8 as it should.
I have found some kind of ugly workaround... I don't know why Rack assumes the encoding is ASCII-8BIT ... anyway, a way is to use string.force_encoding("UTF-8")... but doing this for all params is tedious
I am using Factory Girl but like the machinist syntax. So I wonder, if there is any way creating a named blueprint for class, so that I can have something like that:
User.blueprint(:no_discount_user) do
admin false
hashed_password "226bc1eca359a09f5f1b96e26efeb4bb1aeae383"
is_trader false
name "foolish"
salt "21746899800.223524289203464"
end
User.blueprint(:discount_user) do
admin false
hashed_password "226bc1eca359a09f5f1b96e26efeb4bb1aeae383"
is_trader true
name "deadbeef"
salt "21746899800.223524289203464"
discount_rate { DiscountRate.make(:rate => 20.00) }
end
DiscountRate.blueprint do
rate {10}
not_before ...
not_after ...
end
Is there a way making factory_girl with machinist syntax acting like that? I did not find one. Help appreciated.
Thx in advance
Jason
Hi,
I have followed the Railscast episode 88 to implement a set of dependant drop down menus.
In the students-new view, when the student's year is selected, the javascript figures out which courses are available to that year and offers the selection in a new drop down menu.
My javascript erb file is here:
var courses = new Array();
<% for course in @courses -%>
<%for year in course.years -%>
courses.push(new Array(<%= year.year_id%>, '<%=h course.title%>', <%= course.id%>));
<%end -%>
<% end -%>
function yearSelected() {
year_id = $('student_year_id').getValue();
options = $('student_course_ids').options;
options.length = 1;
courses.each(function(course) {
if (course[0] == year_id) {
options[options.length] = new Option(course[1], course[2]);
}
});
if (options.length == 1) {
$('course_field').hide();
} else {
$('course_field').show();
}
}
document.observe('dom:loaded', function() {
yearSelected();
$('student_year_id').observe('change', yearSelected);
});
Any my view is as follows:
<% form_for(@student) do |f| %>
<%= f.error_messages %>
<p>
<%= f.label :name %><br />
<%= f.text_field :name %>
</p>
<p>
<%= f.label :cid, "CID" %><br />
<%= f.text_field :cid %>
</p>
<p>
<label for="student_year_id">Year:</label>
<%= collection_select(:student, :year_id, Year.all, :id, :title, {:prompt => true})%>
</p>
<p id="course_field">
<label for="student_course_ids">Course:</label>
<%= collection_select(:student, :course_ids, Course.find(:all), :id, :title, {:prompt => true}, {:multiple => true})%>
</p>
<p>
<%= f.submit 'Save' %>
</p>
<% end %>
What I would like to do is to add checkboxes instead of the drop down menu. Any suggestions? I previously was using this method, but was not able to get it to work with the new javascript.
Cheers
Googled for this to no avail. Didn't find anything in the API either. I was expecting some kind of class method or configuration option to set it...
So, rather than calling
from "[email protected]"
for every method, it could be called automatically.
I'm trying to set up a date of birth helper in my Rails app (2.3.5). At present it is like so.
<%= f.date_select :date_of_birth, :start_year => Time.now.year - 110, :end_year => Time.now.year %>
This generates a perfectly functional set of date fields that work just fine but....
They default to today's date which is not ideal for a date of birth field (I'm not sure what is but unless you're running a neonatal unit today's date seems less than ideal). I want it to read Jan 1 2010 instead (or 2011 or whatever year it happens to be). Using the :default option has proven unsuccessful. I've tried many possibilities including;
<%= f.date_select :date_of_birth, :default => {:year => Time.now.year, :month => 'Jan', :day => 1}, :start_year => Time.now.year - 110, :end_year => Time.now.year %>
and
<%= f.date_select :date_of_birth, :default => Time.local(2010,'Jan',1), :start_year => Time.now.year - 110, :end_year => Time.now.year %>
None of this changes the behaviour of the first example. Does the default option actually work as described? It seems that this should be a fairly straightforward thing to do.
Ta.
I need to add different values for each option tag in my collection_select cause Im trying to use this jquery plugin.... How do I do that?
Heres my collection select code
<%= e.collection_select(:id,State.all,:id,:name) %>
The output should be something like
<select name="state[id]" id="state_id" class="selectable">
<option value="">-- select --</option>
<option value="1" title="florida">Florida</option>
<option value="2" title="georgia">Georgia</option>
</select>
Please help.
I posted this to the Cucumber group with no replies, which makes me wonder if this is actually a cucumber issue or not. I'm pretty new to cucumber, and there are a number of things I really don't quite understand about how the cucumber environment is set up and executed within the test environment.
I have a REST API rails app I'm testing with cucumber, using the RestClient gem to generate a post to controller create action. When I run the feature with a hard-coded URL pointing to a running localhost server (my local dev server environment; replacing tickets_url with "http://
localhost/tickets" in the snippet below), my cucumber steps execute as expected. However, when the resource URL resolves to the cucumber host I'm declaring, I get a socket error exception.
getaddrinfo: nodename nor servname provided, or not known (SocketError)
From the steps file:
When /^POS Adapter sends JSON data to the Tickets resource$/ do
ticket = {
:ticket = {
...
}
}
host! "test.host"
puts tickets_url
RestClient.post tickets_url, ticket.to_json, :content_type = :json, :accepts = :json
end
(the "puts" statement prints "http://test.host/tickets")
Using the following gems:
cucumber-0.6.1
webrat-0.6.0
rest-client-1.2.0
I should also say I have a similar set up in another rails app, using test.host as my host, and it seems to work fine. I'd appreciate any insight on what I might be missing in my configuration or what this could be related to.
In my Rails app I have a fairly standard has_many relationship between two entities. A Foo has zero or more Bars; a Bar belongs to exactly one Foo. Both Foo and Bar are identified by a single integer ID value. These values are unique across all of their respective instances.
Bar is existence dependent on Foo: it makes no sense to have a Bar without a Foo.
There's two ways to RESTfully references instances of these classes. Given a Foo.id of "100" and a Bar.id of "200":
Reference each Foo and Bar through their own "top-level" URL routes, like so:
/foo/100
/bar/200
Reference Bar as a nested resource through its instance of Foo:
/foo/100
/foo/100/bar/200
I like the nested routes in #2 as it more closely represents the actual dependency relationship between the entities. However, it does seem to involve a lot of extra work for very little gain. Assuming that I know about a particular Bar, I don't need to be told about a particular Foo; I can derive that from the Bar itself. In fact, I probably should be validating the routed Foo everywhere I go (so that you couldn't do /foo/150/bar/200, assuming Bar 200 is not assigned to Foo 150). Ultimately, I don't see what this brings me.
So, are there any other arguments for or against these two routing schemes?
I'm trying to save the site that a user came from when they sign up. Right now I have a before_filter in my ApplicationController:
before_filter :save_referer
def save_referer
unless is_logged_in?
session['referer'] = request.env["HTTP_REFERER"] unless session['referer']
end
end
Then when a user is created, it checks this session variable and sets it to nil. Sometimes this does not work and I'm worried there might be some unintended things happening with using session like this. Does anyone have a better way? Or some input perhaps?
EDIT: This is the logic I am using to save the referer:
def create
@user = User.new(params[:user])
if @user.save_with(session[:referer])
....
end
User
def save_with(referer)
self.referer = referer unless referer == "null"
self.save
end
Is there any reason why this should not work?
I'm using DHH's auto_complete plugin, but am in the process of updating my dependencies on plugins to gems where feasible. Is there a newer, gemified version of this library, or has another solution emerged as the de facto standard?
I am using the convert command to convert a pdf to multiple pngs, I need the naming conventions to be slide-##.png at the moment they come out like slide-1.png but because there is 20+ slides when I loop through them to add them into the model the order comes up wrong, so it looks like slide-1.png slide-10.png slide-11.png and so on, how can I force convert to use double numbers like 01 02 03 and so forth or is there a better way to loop through them, this is the code I have at the moment
def convert_keynote_to_slides
system('convert -size 640x300 ' + keynote.queued_for_write[:original].path + ' ~/rails/arcticfox/public/system/keynotes/slides/'+File.basename( self.keynote_file_name )+'0%d.png')
slide_basename = File.basename( self.keynote_file_name )
files = Dir.entries('/Users/joshcrowder/rails/arcticfox/public/system/keynotes/slides')
for file in files
#puts file if file.include?(slide_basename +'-')
self.slides.build("slide" => "#{file}") if file.include?(slide_basename)
end
end
I think I'm missing something very obvious and its making my brain hurt.
class User < ActiveRecord::Base
has_one :profile
class Profile < ActiveRecord::Base
has_one :user
belongs_to :team
I have a partial that loops through the users and print some basic info, I'm using this partial in my team show page.
I had originally written this to return users who's profiles were a member of a team.
def show
@team = Team.find_by_id(params[:id])
@profiles= Profile.find(:all, :conditions => ['team_id = ?', @team.id])
@users = User.find_by_id(@profiles.user_id)
end
But quickly realized @profiles was an array, and it looks messy as hell. Stuck as to what my find should look like to select all User who have a profile that is a member of a team.
The partial that is working elsewhere for displaying users looks like this
<% for user in @users%>
<table>
<tr>
<td>
<%= image_tag user.profile.picture.url %>
</td>
<td>
<a href="/users/<%= user.id %>"><%= user.login %></a>
</td>
<td>
<%= user.profile.first_name %> <%= user.profile.second_name %>
</td>
<td>
<%= user.profile.status %>
</td>
</tr>
</table>
<% end %>
Development log output with updated show and relationships
Processing TeamsController#show (for 127.0.0.1 at 2010-03-30 22:06:31) [GET]
Parameters: {"id"=>"1"}
User Load (1.3ms) SELECT * FROM "users" WHERE ("users"."id" = 3) LIMIT 1
Team Load (1.0ms) SELECT * FROM "teams" WHERE ("teams"."id" = 1)
Rendering template within layouts/main
Rendering teams/show
Completed in 75ms (View: 11, DB: 2) | 200 OK [http://localhost/teams/1]
I am trying to test facebook api calls with cucumber. Here is the code.
# app/controller/facebook_users_controller.rb
class FacebookUsersController < ApplicationController
def create
fb_user = facebook_session.user
user = User.new(:facebook_uid => fb_user.uid, :facebook_session_key => facebook_session.session_key
respond_to do |format|
if user.save
format.json { render :json => { :status => 'ok' }.to_json }
end
end
end
end
# features/steps/facebook_connect_step.rb
Given /^I am a facebook connected user$/ do
mock_session = Facebooker::MockSession.create
post('/facebook_user.json')
puts response.code
end
When I run the cucumber step for above step definition, I get a response code of 406 instead of 200. This happens in the cucumber test environment only and not in the browser(development/production).
I'd like to define a method that is available in both my views and my models
Say I have a view helper:
def foo(s)
"hello #{s}"
end
A view might use the helper like this:
<div class="data"><%= foo(@user.name) %></div>
However, this <div> will be updated with a repeating ajax call. I'm using a to_json call in a controller returns data like so:
render :text => @item.to_json(:only => [...], :methods => [:foo])
This means, that I have to have foo defined in my Item model as well:
class Item
def foo
"hello #{name}"
end
end
It'd be nice if I could have a DRY method that could be shared in both my views and my models.
Usage might look like this:
Helper
def say_hello(s)
"hello #{s}"
end
User.rb model
def foo
say_hello(name)
end
Item.rb model
def foo
say_hello(label)
end
View
<div class="data"><%= item.foo %></div>
Controller
def observe
@items = item.find(...)
render :text => @items.to_json(:only=>[...], :methods=>[:foo])
end
IF I'M DUMB,
please let me know.
I don't know the best way to handle this, but I don't want to completely go against best-practices here.
If you can think of a better way, I'm eager to learn!
I installed validation_reflection as a gem and out of the box it picked up on my validates_presence_of validations. But it is not picking up on any of the other default rails validations such as validates_format_of.
I know from the documentation that i am supposed to add something like:
config.reflected_validations << :validates_format_of
to my config/plugins/validation_reflection.rb file (which didn't exist initially). I did this but nothing changed (i restarted the web server in between). I am not sure if it just isn't picking up on my file and loading validation_reflection.rb or if i have done something wrong.
Anyone have any insights?
I'm using the activerecord-jdbc-adapter with ActiveRecord to be able to access a SQLServer database for Rails Application running under jRuby and am having trouble inserting binary data. The Exception I am getting is below. Note I just have a blurb for the binary data from the fixtures that was working fine for MySQL.
ActiveRecord::StatementInvalid: ActiveRecord::ActiveRecordError: Operand type clash: nvarchar is incompatible with image:
INSERT INTO blobstorage_datachunks ([id], [datafile_id], [chunk_number], [data]) VALUES (369397133, 663419003, 0, N'GIF89a@')
When I created the tables the migration had binary and SQLServer used Image instead. We're using Rails 2.3.5, SQLServer Express 2008. What I'm looking for is a way to get the binary data into SQLServer with ActiveRecord.
Thanks in advance for the help.
Hi,
Anyone know how to best implement a multilingual static site using webby?
I would put content for the multiple languages in content/{lang}/{page}.txt for starters, any ideas on the rest?
I've never used webby.
Thanks, Max.