unexpected keyword_end, expecting end-of-input - ruby-on-rails

I get a error: syntax error, unexpected keyword_end, expecting end-of-input. Normally i woudnt ask such questions but im simply cannot the error! Here is my full model code:
The error appears in the method add_gelesen line 48: end Thanks to the community!
class Message < ActiveRecord::Base
attr_accessor :current_user, :current_department
before_save :set_sender, :add_gelesen
def set_sender
self.sender_username = #current_user.username
self.sender_model = #current_user.class.to_s
self.sender_id = #current_user.id
if (recipient_username != #current_department.username) && (recipient_model == 'Department')
self.privat = 0
if Object.const_get(recipient_model).find(recipient_id).has_kontakt?(#current_department.id) == false
Object.const_get(recipient_model).find(recipient_id).kontakt(#current_department.id)
end
end
end
def add_gelesen
if self.privat == true
if recipient_username == #current_department.username
f = JSON.parse(#current_department.gelesen)
#current_department.employees.each.do |c|
w = f["#{c.username}"].nil? ? 0 : f["#{c.username}"]
f["#{c.username}"] = w + 1
end
#current_department.update_column(:gelesen, f.to_json)
else
f = JSON.parse(#current_user.gelesen)
w = f[self.recipient_username].nil? ? 0 : f[self.recipient_username]
f[self.recipient_username] = w + 1
#current_user.update_column(:gelesen, f.to_json)
end
else
u = Object.const_get(self.recipient_model).find(self.recipient_id)
f = JSON.parse(u.gelesen)
#current_department.employees.each.do |c|
w = f["#{c.username}"].nil? ? 0 : f["#{c.username}"]
f["#{c.username}"] = w + 1
end
Department.find(self.recipient_id).employees.each.do |g|
w = f["#{g.username}"].nil? ? 0 : f["#{g.username}"]
f["#{g.username}"] = w + 1
end
u.update_column(:gelesen, f.to_json)
end
end
end

The lines w/ do in them should not have the .
#current_department.employees.each.do |c|
should be
#current_department.employees.each do |c|
do is the keyword for beginning a block, not a method on each

Related

Lua Script problems on Super Nintendo emulation

I'm currently trying to run a lua script to find the future values of a static rng seed from "Fire Emblem - Seisen no Keifu" in the snes9x-1.52-rr-r185 emulator by reading the memory values.
Unfortunately I get the following message when i run the code: "rng.lua:26: attempt to call field 'text' (a nil value)"
The code is below:
emu = snes9x
function get_rng()
return {
step = memory.readbyte(0x7e04a2),
table = memory.readbyterange(0x7e046b,0x37)
}
end
function rand(rng)
rng.step = rng.step + 1
if rng.step >= 0x37 then
for i = 0, 0x36 do
local j if i < 0x18 then j = i+0x1f else j = i-0x18 end
rng.table[i+1] = rng.table[i+1] - rng.table[j+1]
if rng.table[i+1] < 0 then rng.table[i+1] = rng.table[i+1] + 100 end
end
rng.step = 0
end
local res = rng.table[rng.step+1]-1
if res < 0 then res = 99 end
return res
end
while true do
local rng = get_rng()
for i = 1, 0x10 do
gui.text(i*12, 0,string.format("%02x",rng.step))
gui.text(i*12,10,string.format("%2u",rand(rng)))
end
emu.frameadvance()
end
I expected the rng values to be shown on screen but got the aforementioned message.

NoMethodError in controller

Hello I'm new at Ruby and I'm trying to make a method in my Project controller like so:
def update_phase
#project = Project.find(params[:id])
diff = (Date.current.year * 12 + Date.current.month) - (#project.starting.year * 12 + #project.starting.month)
case
when diff >= 30
#project.process = 11
.
.
.
when diff >= 0
#project.process = 1
else
#project.process = 0
end
proc = #project.process.to_f
case
when proc >= 9
#project.phase = "Final"
when proc >= 5
#project.phase = "Desarrollo"
when proc >= 1
#project.phase = "Inicio"
else
#project.phase = "Error en el proceso"
end
end
starting is a timestamp in the model. In my view I have:
<% #project.update_phase %>
but I get the error: "NoMethodError in Projects#show"
how can I fix this?
Depending on what's or where does starting come from, you could use a before_save callback, this way everytime you're going to create a new record, it triggers the update_phase method and assigns the values for process and phase from the current project object:
class Project < ApplicationRecord
before_save :update_phase
...
def update_phase
diff = (Date.current.year * 12 + Date.current.month) - (self.starting.year * 12 + self.starting.month)
case
when diff >= 30
self.process = 11
...
end
proc = self.process.to_f
case
when proc >= 9
self.phase = 'Final'
...
end
end
end

Rails - Simple Loop Not Working

In my controller I am trying to do a bulk insert into a table, in my first attempt it works but the names somehow get mangled as the following: (loop runs 24 times which is what I want)
test-port-name-0-1-2-3-4-5-6-7-8-9-10-11-12-13-14-15-16-17-18-19-20-21
test-port-name-0-1-2-3-4-5-6-7-8-9-10-11-12-13-14-15-16-17-18-19-20
test-port-name-0-1-2-3-4-5-6-7-8-9-10-11-12-13-14-15-16-17-18-19
test-port-name-0-1-2-3-4-5-6-7-8-9-10-11-12-13-14-15-16-17-18
test-port-name-0-1-2-3-4-5-6-7-8-9-10-11-12-13-14-15-16-17
test-port-name-0-1-2-3-4-5-6-7-8-9-10-11-12-13-14-15-16
test-port-name-0-1-2-3-4-5-6-7-8-9-10-11-12-13-14-15
test-port-name-0-1-2-3-4-5-6-7-8-9-10-11-12-13-14
test-port-name-0-1-2-3-4-5-6-7-8-9-10-11-12-13
test-port-name-0-1-2-3-4-5-6-7-8-9-10-11-12
test-port-name-0-1-2-3-4-5-6-7-8-9-10-11
test-port-name-0-1-2-3-4-5-6-7-8-9-10
test-port-name-0-1-2-3-4-5-6-7-8-9
test-port-name-0-1-2-3-4-5-6-7-8
test-port-name-0-1-2-3-4-5-6
test-port-name-0-1-2-3-4-5-6-7
test-port-name-0-1-2-3-4-5
test-port-name-0-1-2-3-4
test-port-name-0-1-2
test-port-name-0-1-2-3
test-port-name-0
test-port-name-0-1
test-port-name-0-1-2-3-4-5-6-7-8-9-10-11-12-13-14-15-16-17-18-19-20-21-22
test-port-name-0-1-2-3-4-5-6-7-8-9-10-11-12-13-14-15-16-17-18-19-20-21-22-23
instead of test-port-name-0 .... test-port-name-23
def bulk_port_import
if request.post?
#attempt create
count = 0
for i in 1..session[:no_ports]
params[:dp][:name] = params[:dp][:name] + '-' + count.to_s
#dp = DevicePort.create params[:dp]
count = count + 1
end
end
#success = "Saved." if #dp.valid?
#error = ""
#dp.errors.each_full {|e| #error += e + ", "}
redirect_to '/device/update/' + params[:dp][:device_id]
end
Different attempt:
def bulk_port_import
if request.post?
#attempt create
i = 0
while i < session[:no_ports] do
params[:dp][:name] = params[:dp][:name] + '-' + i.to_s
#dp = DevicePort.create params[:dp]
i++
end
end
session.delete(:no_ports)
#success = "Saved." if #dp.valid?
#error = ""
#dp.errors.each_full {|e| #error += e + ", "}
redirect_to '/device/update/' + params[:dp][:device_id]
end
but with this I get syntax error, unexpected kEND and I can't see what I'm doing wrong in either case, it's probably something stupid, again.
Its because you are changing params[:dp][:name] in the loop
def bulk_port_import
if request.post?
#attempt create
count = 0
for i in 1..session[:no_ports]
dp_name = params[:dp][:name] + '-' + count.to_s
#dp = DevicePort.create(params[:dp].merge(:name => dp_name))
count = count + 1
end
end
#success = "Saved." if #dp.valid?
#error = ""
#dp.errors.each_full {|e| #error += e + ", "}
redirect_to '/device/update/' + params[:dp][:device_id]
end

archiloque-rest-client: change content-type to multipart/related when posing a file

Using
http://github.com/archiloque/rest-client
When posting a file using this line, the content type is set as
Content-Type: multipart/form-data; boundary=301405
in the header, by default.
RestClient.post '/data', :myfile => File.new("/path/to/image.jpg", 'rb')
I tried this and it still sets the header multipart/form-data.
RestClient.post '/data', :myfile => File.new("/path/to/image.jpg", 'rb'), :content_type => 'multipart/related'
Has anybody tried setting multipart/related?
Or you can use rather new-ish multipart_body gem:
http://steve.dynedge.co.uk/2010/09/19/multipart-body-a-gem-for-working-with-multipart-data/
Ok. I could not find a better alternative, so ended up with the following app.
It is based on this code here.
http://stanislavvitvitskiy.blogspot.com/2008/12/multipart-post-in-ruby.html
Usage:
files = { File.new("myfile1","rb"), File.new("myfile2","rb")}
mpost = Mutipart("main", "<my xml main part content which refers to file names>",files )
mpost.post("our_url","post")
Note: This code is not production ready. It is just functional.
---------------- multipart.rb -------------
require 'net/http'
require 'uri'
require 'pp'
require 'mime/types'
class Multipart
def initialize( main_part_id, main_part_content, file_names )
#file_names = file_names
#main_part_id = main_part_id
#main_part_content = main_part_content
end
def post( to_url, method = :post )
boundary = "###-------#{Time.new}-----####"
parts = []
streams = []
# write main part first
parts << StringPart.new( "--" + boundary + "\r\n")
parts << StringPart.new("Content-Disposition: name=\"#{#main_part_id}\";\"\r\n" +
"Content-ID: #{#main_part_id}\r\n\r\n"+
"Content-Type: application/xml\r\n\r\n" +
#main_part_content + "\r\n\r\n")
parts << StringPart.new( "\r\n--" + boundary + "\r\n")
#file_names.each do |param_name, filestream|
raise 'mutlipartsend: empty file object' if filestream.blank?
filename= filestream.respond_to?(:original_path) ? filestream.original_path : filestream.path
ctype = filestream.respond_to?(:content_type) ? filestream.content_type: nil
fsize = filestream.respond_to?(:lstat) ? filestream.lstat.size : filestream.size
if !ctype
begin
pos = filename.rindex('/') # if filename is a path
fname = filename[pos + 1, filename.length - pos]
mm = MIME::Types.type_for(fname)
ctype = mm.first.content_type if !mm.blank?
rescue Exception => e
p e.message
end
end
if !ctype
ctype= 'application/binary'
p "mutlipartsend: failed to determine contenttype for #{filename}. using application/binary"
end
parts << StringPart.new("Content-Disposition: name=\"" + param_name.to_s + "\"; filename=\"" + filename + "\"\r\n" +
"Content-Type: #{ctype}\r\n\r\n")
#"Content-Type: application/binary\r\n\r\n")
begin
stream = File.open(filestream.path,"rb")
streams << stream
parts << StreamPart.new(stream, fsize)
parts << StringPart.new( "\r\n--" + boundary + "\r\n" )
rescue Exception => e
p 'failed to load filestream '+ filestream.path
p e.message
raise 'failed to load filestream ' + e.message
end
end
post_stream = MultipartStream.new( parts )
url = URI.parse( to_url )
req = method == :post ? Net::HTTP::Post.new(url.path) : Net::HTTP::Put.new(url.path)
req.content_length = post_stream.size
req.content_type = 'multipart/mixed; boundary=' + boundary
req["myheader1"] = 'header1'
req["myheader2"] = 'header2'
req.body_stream = post_stream
res = Net::HTTP.new(url.host, url.port).start {|http| http.request(req) }
streams.each do |stream|
stream.close();
end
res
end
end
class StreamPart
def initialize( stream, size )
#stream, #size = stream, size
end
def size
#size
end
def read( offset, how_much )
#stream.read( how_much )
end
end
class StringPart
def initialize ( str )
#str = str
end
def size
#str.length
end
def read ( offset, how_much )
#str[offset, how_much]
end
end
class MultipartStream
def initialize( parts )
#parts = parts
#part_no = 0;
#part_offset = 0;
end
def size
total = 0
#parts.each do |part|
total += part.size
end
total
end
def read ( how_much )
if #part_no >= #parts.size
return nil;
end
how_much_current_part = #parts[#part_no].size - #part_offset
how_much_current_part = if how_much_current_part > how_much
how_much
else
how_much_current_part
end
how_much_next_part = how_much - how_much_current_part
current_part = #parts[#part_no].read(#part_offset, how_much_current_part )
if how_much_next_part > 0
#part_no += 1
#part_changed=true
#part_offset = 0
next_part = read( how_much_next_part )
current_part + if next_part
next_part
else
''
end
else
#part_offset += how_much_current_part
current_part
end
end
end

Help refactoring this nasty Ruby if/else statement

So I have this big, hairy if/else statement. I pass a tracking number to it, and then it determines what type of tracking number it is.
How can I simplify this thing? Specifically wanting to reduce the number of lines of codes.
if num_length < 8
tracking_service = false
else
if number[1, 1] == 'Z'
tracking_service = 'ups'
elsif number[0, 1] == 'Q'
tracking_service = 'dhl'
elsif number[0, 2] == '96' && num_length == 22
tracking_service = 'fedex'
elsif number[0, 1] == 'H' && num_length == 11
tracking_service = 'ups'
elsif number[0, 1] == 'K' && num_length == 11
tracking_service = 'ups'
elsif num_length == 18 || num_length == 20
check_response(number)
else
case num_length
when 17
tracking_service = 'dhlgm'
when 13,20,22,30
tracking_service = 'usps'
when 12,15,19
tracking_service = 'fedex'
when 10,11
tracking_service = 'dhl'
else
tracking_service = false
end
end
end
Yes, I know. It's nasty.
Try this. I rewrote it using case and regular expressions. I also used :symbols instead of "strings" for the return values, but you can change that back.
tracking_service = case number
when /^.Z/ then :ups
when /^Q/ then :dhl
when /^96.{20}$/ then :fedex
when /^[HK].{10}$/ then :ups
else
check_response(number) if num_length == 18 || num_length == 20
case num_length
when 17 then :dhlgm
when 13, 20, 22, 30 then :usps
when 12, 15, 19 then :fedex
when 10, 11 then :dhl
else false
end
end
Depending on whether or not the tracking code is a ruby object, you could also put helper's in it's class definition:
class TrackingCode < String
# not sure if this makes sense for your use case
def ups?
self[1,1] == 'Z'
end
def dhl?
self[0,1] == 'Q'
end
def fedex?
self.length == 22 && self[0, 2] == '96'
end
# etc...
end
Then your conditional becomes:
if number.ups?
# ...
elsif number.dhl?
# ...
elseif number.fedex?
end
One simplified conditional where you are operating on the implied feature of the tracking code. Likewise, if you were to take a looping approach, your loop would also be cleaner:
%w(ups? dhl? fedex?).each do |is_code|
return if number.send(is_code)
end
or even:
%w(ups? dhl? fedex?).each do |is_code|
yield if number.send(is_code)
end
This method looks like it was written for speed. You can use a minhash as a substitute, but I think the code is fairly clean and doesn't require a refactor. Rubyists tend to be disgusted by needless structure, but oftentimes it's needed to model real-world situations and/or provides a performance boost. The keyword should be needless.
Whilst longer than jtbandes solution, you might like this as it's a bit more declarative:
class Condition
attr_reader :service_name, :predicate
def initialize(service_name, &block)
#service_name = service_name
#predicate = block
end
end
CONDITIONS = [
Condition.new('ups') { |n| n[1] == 'Z' },
Condition.new('dhl') { |n| n[0] == 'Q' },
Condition.new('fedex') { |n| n[0..1] == '96' && n.size == 22 },
Condition.new('ups') { |n| n[0] == 'H' && n.size == 11 },
Condition.new('ups') { |n| n[0] == 'K' && n.size == 11 },
Condition.new('dhlgm') { |n| n.size == 17 },
Condition.new('usps') { |n| [13, 20, 22, 30].include?(n.size) },
Condition.new('fedex') { |n| [12, 15, 19].include?(n.size) },
Condition.new('dhl') { |n| [10, 11].include?(n.size) },
]
def tracking_service(tracking_number)
result = CONDITIONS.find do |condition|
condition.predicate.call(tracking_number)
end
result.service_name if result
end
I haven't dealt with the check_response method call here as I feel you should probably handle that elsewhere (assuming it does something other than return a tracking service name).
I believe this is sufficiently complex to deserve its own method.
BTW, if the length is 20 then the original function returns whatever check_response(n) returns, yet then attempts (and will always fail) to return 'usps'.
#lenMap = Hash.new false
#lenMap[17] = 'dhlgm'
#lenMap[13] = #lenMap[20] = #lenMap[22] = #lenMap[30] = 'usps'
#lenMap[12] = #lenMap[15] = #lenMap[19] = 'fedex'
#lenMap[10] = #lenMap[11] = 'dhl'
def ts n
len = n.length
return false if len < 8
case n
when /^.Z/
return 'ups'
when /^Q/
return 'dhl'
when /^96....................$/
return 'fedex'
when /^[HK]..........$/
return 'ups'
end
return check_response n if len == 18 or len == 20
return #lenMap[len]
end
# test code...
def check_response n
return 'check 18/20 '
end
%w{ 1Zwhatever Qetcetcetc 9634567890123456789012 H2345678901
K2345678901 hownowhownowhownow hownowhownowhownow90
12345678901234567
1234567890123
12345678901234567890
1234567890123456789012
123456789012345678901234567890
123456789012
123456789012345
1234567890123456789
1234567890
12345678901 }.each do |s|
puts "%32s %s" % [s, (ts s).to_s]
end

Resources