Latest Ruby Questions on Stack Overflow

Parse markdown indented code block gets stuck in recursion

Asked by JMH | Score: 2 | Answers: 1

I am trying to parse Markdown using a grammar written with Parslet. However, I cannot get past indented code blocks because everything I tried so far got stuck in recursion. They look like this:

    This is a indented code block.
    Second line.

    Code block continues after blank line.

    There can be any number of chunks, 
    separated by not more than one blank line.

In order to solve this I wrote a minimal example which replaces the lines (including \n) with a and blank lines (\n\n) with spaces, eg: a aaa aa.

# recurring_group_parser.rb

require 'parslet'
require 'rspec'
require 'parslet/rig/rspec'

class RecurringGroupParser < Parslet::Parser
  root(:block)

  rule :block do
    chunk.repeat(1,3)
  end

  rule :chunk do
    str('a').repeat(1,3) >> space
  end

  rule :space do
    str(' ') | chunk.absent?
  end
end

describe RecurringGroupParser do
  it 'should parse a' do
    is_expected.to parse "a"
  end

  it 'should parse aa' do
    is_expected.to parse "aa"
  end

  it 'should parse aaa' do
    is_expected.to parse "aaa"
  end

  it 'should parse a a' do
    is_expected.to parse "a a"
  end

  it 'should parse aa a' do
    is_expected.to parse "aa a"
  end

  it 'should parse aaa a' do
    is_expected.to parse "aaa a"
  end

  it 'should parse a aa' do
    is_expected.to parse "a aa"
  end

  it 'should parse a aaa' do
    is_expected.to parse "a aaa"
  end

  it 'should parse aa a' do
    is_expected.to parse "aa a"
  end

  it 'should parse aa aa' do
    is_expected.to parse "aa aa"
  end

  it 'should parse aa aaa' do
    is_expected.to parse "aa aaa"
  end

  it 'should parse aaa aa' do
    is_expected.to parse "aaa aa"
  end

  it 'should parse aaa aaa' do
    is_expected.to parse "aaa aaa"
  end

  it 'should parse a a a' do
    is_expected.to parse "a a a"
  end

  it 'should parse aa a a' do
    is_expected.to parse "aa a a"
  end

  it 'should parse aaa a a' do
    is_expected.to parse "aaa a a"
  end

  it 'should parse a aa a' do
    is_expected.to parse "a aa a"
  end

  it 'should parse aa aa a' do
    is_expected.to parse "aa aa a"
  end

  it 'should parse aaa aa a' do
    is_expected.to parse "aaa aa a"
  end

  it 'should parse a aaa a' do
    is_expected.to parse "a aaa a"
  end

  it 'should parse aa aaa a' do
    is_expected.to parse "aa aaa a"
  end

  it 'should parse aaa aaa a' do
    is_expected.to parse "aaa aaa a"
  end

  it 'should parse a a aa' do
    is_expected.to parse "a a aa"
  end

  it 'should parse aa a aa' do
    is_expected.to parse "aa a aa"
  end

  it 'should parse aaa a aa' do
    is_expected.to parse "aaa a aa"
  end

  it 'should parse a aa aa' do
    is_expected.to parse "a aa aa"
  end

  it 'should parse aa aa aa' do
    is_expected.to parse "aa aa aa"
  end

  it 'should parse aaa aa aa' do
    is_expected.to parse "aaa aa aa"
  end

  it 'should parse a aaa aa' do
    is_expected.to parse "a aaa aa"
  end

  it 'should parse aa aaa aa' do
    is_expected.to parse "aa aaa aa"
  end

  it 'should parse aaa aaa aa' do
    is_expected.to parse "aaa aaa aa"
  end

  it 'should parse a a aaa' do
    is_expected.to parse "a a aaa"
  end

  it 'should parse aa a aaa' do
    is_expected.to parse "aa a aaa"
  end

  it 'should parse aaa a aaa' do
    is_expected.to parse "aaa a aaa"
  end

  it 'should parse a aa aaa' do
    is_expected.to parse "a aa aaa"
  end

  it 'should parse aa aa aaa' do
    is_expected.to parse "aa aa aaa"
  end

  it 'should parse aaa aa aaa' do
    is_expected.to parse "aaa aa aaa"
  end

  it 'should parse a aaa aaa' do
    is_expected.to parse "a aaa aaa"
  end

  it 'should parse aa aaa aaa' do
    is_expected.to parse "aa aaa aaa"
  end

  it 'should parse aaa aaa aaa' do
    is_expected.to parse "aaa aaa aaa"
  end
end

Running rspec recurring_group_parser.rb works fine. Only when I put the newlines back in, it stalls:

# recurring_group_parser.rb

require 'parslet'
require 'rspec'
require 'parslet/rig/rspec'

class RecurringGroupParser < Parslet::Parser
  root(:block)

  rule :block do
    chunk.repeat(1,3)
  end

  rule :chunk do
    line.repeat(1,3) >> blank_line
  end

  rule :line do
    str('a') >> newline
  end

  rule :blank_line do
    newline.repeat(2) | chunk.absent?
  end

  rule :newline do
    str("\n") | any.absent?
  end
end

describe RecurringGroupParser do
  it 'should parse a' do
    is_expected.to parse "a"
  end

  it 'should parse aa' do
    is_expected.to parse "a\na"
  end

  it 'should parse aaa' do
    is_expected.to parse "a\na\na"
  end

  it 'should parse a a' do
    is_expected.to parse "a\n\na"
  end

  it 'should parse aa a' do
    is_expected.to parse "a\na\n\na"
  end

  it 'should parse aaa a' do
    is_expected.to parse "a\naa\n\na"
  end

  it 'should parse a aa' do
    is_expected.to parse "a\n\na\na"
  end

  it 'should parse a aaa' do
    is_expected.to parse "a\n\na\na\na"
  end

  it 'should parse aa a' do
    is_expected.to parse "a\na\n\na"
  end

  it 'should parse aa aa' do
    is_expected.to parse "a\na\n\na\na"
  end

  it 'should parse aa aaa' do
    is_expected.to parse "a\na\n\na\na\na"
  end

  it 'should parse aaa aa' do
    is_expected.to parse "a\naa\n\na\na"
  end

  it 'should parse aaa aaa' do
    is_expected.to parse "a\naa\n\na\na\na"
  end

  it 'should parse a a a' do
    is_expected.to parse "a\n\na\n\na"
  end

  it 'should parse aa a a' do
    is_expected.to parse "a\na\n\na\n\na"
  end

  it 'should parse aaa a a' do
    is_expected.to parse "a\naa\n\na\n\na"
  end

  it 'should parse a aa a' do
    is_expected.to parse "a\n\na\na\n\na"
  end

  it 'should parse aa aa a' do
    is_expected.to parse "a\na\n\na\na\n\na"
  end

  it 'should parse aaa aa a' do
    is_expected.to parse "a\naa\n\na\na\n\na"
  end

  it 'should parse a aaa a' do
    is_expected.to parse "a\n\na\naa\n\na"
  end

  it 'should parse aa aaa a' do
    is_expected.to parse "a\na\n\na\naa\n\na"
  end

  it 'should parse aaa aaa a' do
    is_expected.to parse "a\naa\n\na\naa\n\na"
  end

  it 'should parse a a aa' do
    is_expected.to parse "a\n\na\n\na\na"
  end

  it 'should parse aa a aa' do
    is_expected.to parse "a\na\n\na\n\na\na"
  end

  it 'should parse aaa a aa' do
    is_expected.to parse "a\naa\n\na\n\na\na"
  end

  it 'should parse a aa aa' do
    is_expected.to parse "a\n\na\na\n\na\na"
  end

  it 'should parse aa aa aa' do
    is_expected.to parse "a\na\n\na\na\n\na\na"
  end

  it 'should parse aaa aa aa' do
    is_expected.to parse "a\naa\n\na\na\n\na\na"
  end

  it 'should parse a aaa aa' do
    is_expected.to parse "a\n\na\naa\n\na\na"
  end

  it 'should parse aa aaa aa' do
    is_expected.to parse "a\na\n\na\naa\n\na\na"
  end

  it 'should parse aaa aaa aa' do
    is_expected.to parse "a\naa\n\na\naa\n\na\na"
  end

  it 'should parse a a aaa' do
    is_expected.to parse "a\n\na\n\na\na\na"
  end

  it 'should parse aa a aaa' do
    is_expected.to parse "a\na\n\na\n\na\na\na"
  end

  it 'should parse aaa a aaa' do
    is_expected.to parse "a\naa\n\na\n\na\na\na"
  end

  it 'should parse a aa aaa' do
    is_expected.to parse "a\n\na\na\n\na\na\na"
  end

  it 'should parse aa aa aaa' do
    is_expected.to parse "a\na\n\na\na\n\na\na\na"
  end

  it 'should parse aaa aa aaa' do
    is_expected.to parse "a\naa\n\na\na\n\na\na\na"
  end

  it 'should parse a aaa aaa' do
    is_expected.to parse "a\n\na\naa\n\na\na\na"
  end

  it 'should parse aa aaa aaa' do
    is_expected.to parse "a\na\n\na\naa\n\na\na\na"
  end

  it 'should parse aaa aaa aaa' do
    is_expected.to parse "a\naa\n\na\naa\n\na\na\na"
  end
end

To simplify this, lines can only consist of a single a and are not indented but that can easily be changed later and are not related to the failure to finish parsing. I am also pretty sure that there is a collision between chunk.absent? in rule :blank_line and any.absent? in rule :newline but I have no idea how to fix this and provide criteria to break the recursion. Any help wanted!

Answers:

In this case newline can be eof. In which case newline. repeat(2) repeatedly matches eof. You want "repeat(2,2)". You can made these bugs easy to find :)... Just use my fork.

You can detect how it's looping by using my fork of parslet. It catches loops and tells you what's happening. It's slower than the usual parslet, so switch back for production parsing.

Use this Gemfile:

source "https://rubygems.org"

gem "parslet" , :git => "https://github.com/NigelThorne/parslet.git"
gem 'rspec'

And you get these results:

 9:23:40.20 > bundle exec rspec parser.rb
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF

Failures:

  1) RecurringGroupParser should parse a
     Failure/Error: is_expected.to parse "a"
     RuntimeError:
       Grammar contains an infinite loop applying 'NEWLINE{2, }' at char position 1
       ...a<-- here
     # ./parser.rb:33:in `block (2 levels) in <top (required)>'

  2) RecurringGroupParser should parse aa
     Failure/Error: is_expected.to parse "a\na"
     RuntimeError:
       Grammar contains an infinite loop applying 'NEWLINE{2, }' at char position 3
       ...a
       a<-- here
     # ./parser.rb:37:in `block (2 levels) in <top (required)>'

  3) RecurringGroupParser should parse aaa
     Failure/Error: is_expected.to parse "a\na\na"
     RuntimeError:
       Grammar contains an infinite loop applying 'NEWLINE{2, }' at char position 5
       ...a
       a
       a<-- here
     # ./parser.rb:41:in `block (2 levels) in <top (required)>'

  4) RecurringGroupParser should parse a a
     Failure/Error: is_expected.to parse "a\n\na"
       expected BLOCK to be able to parse "a\n\na"
     # ./parser.rb:45:in `block (2 levels) in <top (required)>'

  5) RecurringGroupParser should parse aa a
     Failure/Error: is_expected.to parse "a\na\n\na"
       expected BLOCK to be able to parse "a\na\n\na"
     # ./parser.rb:49:in `block (2 levels) in <top (required)>'

  6) RecurringGroupParser should parse aaa a
     Failure/Error: is_expected.to parse "a\naa\n\na"
       expected BLOCK to be able to parse "a\naa\n\na"
     # ./parser.rb:53:in `block (2 levels) in <top (required)>'

  7) RecurringGroupParser should parse a aa
     Failure/Error: is_expected.to parse "a\n\na\na"
       expected BLOCK to be able to parse "a\n\na\na"
     # ./parser.rb:57:in `block (2 levels) in <top (required)>'

  8) RecurringGroupParser should parse a aaa
     Failure/Error: is_expected.to parse "a\n\na\na\na"
       expected BLOCK to be able to parse "a\n\na\na\na"
     # ./parser.rb:61:in `block (2 levels) in <top (required)>'

  9) RecurringGroupParser should parse aa a
     Failure/Error: is_expected.to parse "a\na\n\na"
       expected BLOCK to be able to parse "a\na\n\na"
     # ./parser.rb:65:in `block (2 levels) in <top (required)>'

  10) RecurringGroupParser should parse aa aa
     Failure/Error: is_expected.to parse "a\na\n\na\na"
       expected BLOCK to be able to parse "a\na\n\na\na"
     # ./parser.rb:69:in `block (2 levels) in <top (required)>'

  11) RecurringGroupParser should parse aa aaa
     Failure/Error: is_expected.to parse "a\na\n\na\na\na"
       expected BLOCK to be able to parse "a\na\n\na\na\na"
     # ./parser.rb:73:in `block (2 levels) in <top (required)>'

  12) RecurringGroupParser should parse aaa aa
     Failure/Error: is_expected.to parse "a\naa\n\na\na"
       expected BLOCK to be able to parse "a\naa\n\na\na"
     # ./parser.rb:77:in `block (2 levels) in <top (required)>'

  13) RecurringGroupParser should parse aaa aaa
     Failure/Error: is_expected.to parse "a\naa\n\na\na\na"
       expected BLOCK to be able to parse "a\naa\n\na\na\na"
     # ./parser.rb:81:in `block (2 levels) in <top (required)>'

  14) RecurringGroupParser should parse a a a
     Failure/Error: is_expected.to parse "a\n\na\n\na"
       expected BLOCK to be able to parse "a\n\na\n\na"
     # ./parser.rb:85:in `block (2 levels) in <top (required)>'

  15) RecurringGroupParser should parse aa a a
     Failure/Error: is_expected.to parse "a\na\n\na\n\na"
       expected BLOCK to be able to parse "a\na\n\na\n\na"
     # ./parser.rb:89:in `block (2 levels) in <top (required)>'

  16) RecurringGroupParser should parse aaa a a
     Failure/Error: is_expected.to parse "a\naa\n\na\n\na"
       expected BLOCK to be able to parse "a\naa\n\na\n\na"
     # ./parser.rb:93:in `block (2 levels) in <top (required)>'

  17) RecurringGroupParser should parse a aa a
     Failure/Error: is_expected.to parse "a\n\na\na\n\na"
       expected BLOCK to be able to parse "a\n\na\na\n\na"
     # ./parser.rb:97:in `block (2 levels) in <top (required)>'

  18) RecurringGroupParser should parse aa aa a
     Failure/Error: is_expected.to parse "a\na\n\na\na\n\na"
       expected BLOCK to be able to parse "a\na\n\na\na\n\na"
     # ./parser.rb:101:in `block (2 levels) in <top (required)>'

  19) RecurringGroupParser should parse aaa aa a
     Failure/Error: is_expected.to parse "a\naa\n\na\na\n\na"
       expected BLOCK to be able to parse "a\naa\n\na\na\n\na"
     # ./parser.rb:105:in `block (2 levels) in <top (required)>'

  20) RecurringGroupParser should parse a aaa a
     Failure/Error: is_expected.to parse "a\n\na\naa\n\na"
       expected BLOCK to be able to parse "a\n\na\naa\n\na"
     # ./parser.rb:109:in `block (2 levels) in <top (required)>'

  21) RecurringGroupParser should parse aa aaa a
     Failure/Error: is_expected.to parse "a\na\n\na\naa\n\na"
       expected BLOCK to be able to parse "a\na\n\na\naa\n\na"
     # ./parser.rb:113:in `block (2 levels) in <top (required)>'

  22) RecurringGroupParser should parse aaa aaa a
     Failure/Error: is_expected.to parse "a\naa\n\na\naa\n\na"
       expected BLOCK to be able to parse "a\naa\n\na\naa\n\na"
     # ./parser.rb:117:in `block (2 levels) in <top (required)>'

  23) RecurringGroupParser should parse a a aa
     Failure/Error: is_expected.to parse "a\n\na\n\na\na"
       expected BLOCK to be able to parse "a\n\na\n\na\na"
     # ./parser.rb:121:in `block (2 levels) in <top (required)>'

  24) RecurringGroupParser should parse aa a aa
     Failure/Error: is_expected.to parse "a\na\n\na\n\na\na"
       expected BLOCK to be able to parse "a\na\n\na\n\na\na"
     # ./parser.rb:125:in `block (2 levels) in <top (required)>'

  25) RecurringGroupParser should parse aaa a aa
     Failure/Error: is_expected.to parse "a\naa\n\na\n\na\na"
       expected BLOCK to be able to parse "a\naa\n\na\n\na\na"
     # ./parser.rb:129:in `block (2 levels) in <top (required)>'

  26) RecurringGroupParser should parse a aa aa
     Failure/Error: is_expected.to parse "a\n\na\na\n\na\na"
       expected BLOCK to be able to parse "a\n\na\na\n\na\na"
     # ./parser.rb:133:in `block (2 levels) in <top (required)>'

  27) RecurringGroupParser should parse aa aa aa
     Failure/Error: is_expected.to parse "a\na\n\na\na\n\na\na"
       expected BLOCK to be able to parse "a\na\n\na\na\n\na\na"
     # ./parser.rb:137:in `block (2 levels) in <top (required)>'

  28) RecurringGroupParser should parse aaa aa aa
     Failure/Error: is_expected.to parse "a\naa\n\na\na\n\na\na"
       expected BLOCK to be able to parse "a\naa\n\na\na\n\na\na"
     # ./parser.rb:141:in `block (2 levels) in <top (required)>'

  29) RecurringGroupParser should parse a aaa aa
     Failure/Error: is_expected.to parse "a\n\na\naa\n\na\na"
       expected BLOCK to be able to parse "a\n\na\naa\n\na\na"
     # ./parser.rb:145:in `block (2 levels) in <top (required)>'

  30) RecurringGroupParser should parse aa aaa aa
     Failure/Error: is_expected.to parse "a\na\n\na\naa\n\na\na"
       expected BLOCK to be able to parse "a\na\n\na\naa\n\na\na"
     # ./parser.rb:149:in `block (2 levels) in <top (required)>'

  31) RecurringGroupParser should parse aaa aaa aa
     Failure/Error: is_expected.to parse "a\naa\n\na\naa\n\na\na"
       expected BLOCK to be able to parse "a\naa\n\na\naa\n\na\na"
     # ./parser.rb:153:in `block (2 levels) in <top (required)>'

  32) RecurringGroupParser should parse a a aaa
     Failure/Error: is_expected.to parse "a\n\na\n\na\na\na"
       expected BLOCK to be able to parse "a\n\na\n\na\na\na"
     # ./parser.rb:157:in `block (2 levels) in <top (required)>'

  33) RecurringGroupParser should parse aa a aaa
     Failure/Error: is_expected.to parse "a\na\n\na\n\na\na\na"
       expected BLOCK to be able to parse "a\na\n\na\n\na\na\na"
     # ./parser.rb:161:in `block (2 levels) in <top (required)>'

  34) RecurringGroupParser should parse aaa a aaa
     Failure/Error: is_expected.to parse "a\naa\n\na\n\na\na\na"
       expected BLOCK to be able to parse "a\naa\n\na\n\na\na\na"
     # ./parser.rb:165:in `block (2 levels) in <top (required)>'

  35) RecurringGroupParser should parse a aa aaa
     Failure/Error: is_expected.to parse "a\n\na\na\n\na\na\na"
       expected BLOCK to be able to parse "a\n\na\na\n\na\na\na"
     # ./parser.rb:169:in `block (2 levels) in <top (required)>'

  36) RecurringGroupParser should parse aa aa aaa
     Failure/Error: is_expected.to parse "a\na\n\na\na\n\na\na\na"
       expected BLOCK to be able to parse "a\na\n\na\na\n\na\na\na"
     # ./parser.rb:173:in `block (2 levels) in <top (required)>'

  37) RecurringGroupParser should parse aaa aa aaa
     Failure/Error: is_expected.to parse "a\naa\n\na\na\n\na\na\na"
       expected BLOCK to be able to parse "a\naa\n\na\na\n\na\na\na"
     # ./parser.rb:177:in `block (2 levels) in <top (required)>'

  38) RecurringGroupParser should parse a aaa aaa
     Failure/Error: is_expected.to parse "a\n\na\naa\n\na\na\na"
       expected BLOCK to be able to parse "a\n\na\naa\n\na\na\na"
     # ./parser.rb:181:in `block (2 levels) in <top (required)>'

  39) RecurringGroupParser should parse aa aaa aaa
     Failure/Error: is_expected.to parse "a\na\n\na\naa\n\na\na\na"
       expected BLOCK to be able to parse "a\na\n\na\naa\n\na\na\na"
     # ./parser.rb:185:in `block (2 levels) in <top (required)>'

  40) RecurringGroupParser should parse aaa aaa aaa
     Failure/Error: is_expected.to parse "a\naa\n\na\naa\n\na\na\na"
       expected BLOCK to be able to parse "a\naa\n\na\naa\n\na\na\na"
     # ./parser.rb:189:in `block (2 levels) in <top (required)>'

Finished in 0.01702 seconds (files took 0.26725 seconds to load)
40 examples, 40 failures    

see this question on parsing indentation with Parslet.

– Nigel Thorne | Score: 3

How to XMLRPC::Client authentication

Asked by bwizzy | Score: 1 | Answers: 2

I need to make an XMLRPC request that has to be authenticated, and have found limited documentation on the authentication side of XMLRPC. What's the best way to go about this? Right now I'm using the code below but still getting an authentication failure. Is there a different way to specify the client, then call a secondary auth method?

client = XMLRPC::Client.new(@xmlrpc_url, "/xmlrpc.php", "443", nil, nil, @username, @password, true, 900)
Answers:

Looking into IXR http://scripts.incutio.com/xmlrpc/basic-server-construction.php it shows how to do basic authentication but doesn't look very secure

– Phill Pafford | Score: 0

...I'm using the code below but still getting an authentication failure

Double-check that the remote webserver is accepting HTTP Basic Authentication for the resource /xmlrpc.php, and that it further accepts your @username and @password.

Per the docs, your XMLRPC incantation for an RPC client.call("bwizzy") will generate something with Basic Auth like this:

POST /xmlrpc.php HTTP/1.1
User-Agent: XMLRPC::Client (Ruby 1.9.1)
Content-Type: text/xml; charset=utf-8
Content-Length: 88
Connection: keep-alive
Authorization: Basic c3RhY2s6b3ZlcmZsb3c=
Accept: */*
Host: localhost

<?xml version="1.0"><methodCall><methodName>bwizzy</methodName></params></methodCall>

(Please don't complain to me about the order of those headers -- that's what I see on the wire! :))

Now, XML-RPC does not itself provide for authentication, so you have a few general options:

  1. Use typical "web auth" techniques
    HTTP Authorization schemes, like you are currently using. Trusted client-side certs. Cookie authentication tokens. Etc.
    Typical web auth techniques carry common risks, however. Poke around SO for more guidance here.

  2. Extend the RPC functions to support user-defined auth
    For example, the RPC call bwizzy might take a username and password as arguments.
    Or a login RPC function might generate a time-limited token to be used as a Cookie.
    This approach is invasive -- now your RPC calls have to be auth-aware -- and error-prone -- now you have to implement auth yourself.

  3. Extend XML-RPC itself
    The XML RPC calls could be themselves signed or signed and encrypted, for example, ala SOAP's digital signatures

– pilcrow | Score: 0

Count, size, length...too many choices in Ruby?

Asked by cbmeeks | Score: 156 | Answers: 6

I can't seem to find a definitive answer on this and I want to make sure I understand this to the "n'th level" :-)


    a = { "a" => "Hello", "b" => "World" }
    a.count  # 2
    a.size   # 2
    a.length # 2
    
    a = [ 10, 20 ]
    a.count  # 2
    a.size   # 2
    a.length # 2

So which to use? If I want to know if a has more than one element then it doesn't seem to matter but I want to make sure I understand the real difference. This applies to arrays too. I get the same results.

Also, I realize that count/size/length have different meanings with ActiveRecord. I'm mostly interested in pure Ruby (1.92) right now but if anyone wants to chime in on the difference AR makes that would be appreciated as well.

Answers:

We have a several ways to find out how many elements in an array like .length, .count and .size. However, It's better to use array.size rather than array.count. Because .size is better in performance.

– Venkat M | Score: 2

Adding more to Mark Byers answer. In Ruby the method array.size is an alias to Array#length method. There is no technical difference in using any of these two methods. Possibly you won't see any difference in performance as well. However, the array.count also does the same job but with some extra functionalities Array#count

It can be used to get total no of elements based on some condition. Count can be called in three ways:

Array#count # Returns number of elements in Array

Array#count n # Returns number of elements having value n in Array

Array#count{|i| i.even?} Returns count based on condition invoked on each element array

array = [1,2,3,4,5,6,7,4,3,2,4,5,6,7,1,2,4]

array.size     # => 17
array.length   # => 17
array.count    # => 17

Here all three methods do the same job. However here is where the count gets interesting.

Let us say, I want to find how many array elements does the array contains with value 2

array.count 2    # => 3

The array has a total of three elements with value as 2.

Now, I want to find all the array elements greater than 4

array.count{|i| i > 4}   # =>6

The array has total 6 elements which are > than 4.

I hope it gives some info about count method.

– Prabhakar--PK | Score: 1

For arrays and hashes size is an alias for length. They are synonyms and do exactly the same thing.

count is more versatile - it can take an element or predicate and count only those items that match.

> [1,2,3].count{|x| x > 2 }
=> 1

In the case where you don't provide a parameter to count it has basically the same effect as calling length. There can be a performance difference though.

We can see from the source code for Array that they do almost exactly the same thing. Here is the C code for the implementation of array.length:

static VALUE
rb_ary_length(VALUE ary)
{
    long len = RARRAY_LEN(ary);
    return LONG2NUM(len);
}

And here is the relevant part from the implementation of array.count:

static VALUE
rb_ary_count(int argc, VALUE *argv, VALUE ary)
{
    long n = 0;

    if (argc == 0) {
        VALUE *p, *pend;

        if (!rb_block_given_p())
            return LONG2NUM(RARRAY_LEN(ary));

        // etc..
    }
}

The code for array.count does a few extra checks but in the end calls the exact same code: LONG2NUM(RARRAY_LEN(ary)).

Hashes (source code) on the other hand don't seem to implement their own optimized version of count so the implementation from Enumerable (source code) is used, which iterates over all the elements and counts them one-by-one.

In general I'd advise using length (or its alias size) rather than count if you want to know how many elements there are altogether.


Regarding ActiveRecord, on the other hand, there are important differences. check out this post:

– Mark Byers | Score: 208

I found a good answare at http://blog.hasmanythrough.com/2008/2/27/count-length-size

In ActiveRecord, there are several ways to find out how many records are in an association, and there are some subtle differences in how they work.

post.comments.count - Determine the number of elements with an SQL COUNT query. You can also specify conditions to count only a subset of the associated elements (e.g. :conditions => {:author_name => "josh"}). If you set up a counter cache on the association, #count will return that cached value instead of executing a new query.

post.comments.length - This always loads the contents of the association into memory, then returns the number of elements loaded. Note that this won't force an update if the association had been previously loaded and then new comments were created through another way (e.g. Comment.create(...) instead of post.comments.create(...)).

post.comments.size - This works as a combination of the two previous options. If the collection has already been loaded, it will return its length just like calling #length. If it hasn't been loaded yet, it's like calling #count.

Also I have a personal experience:

<%= h(params.size.to_s) %> # works_like_that !
<%= h(params.count.to_s) %> # does_not_work_like_that !

– profimedica | Score: 5

There is a crucial difference for applications which make use of database connections.

When you are using many ORMs (ActiveRecord, DataMapper, etc.) the general understanding is that .size will generate a query that requests all of the items from the database ('select * from mytable') and then give you the number of items resulting, whereas .count will generate a single query ('select count(*) from mytable') which is considerably faster.

Because these ORMs are so prevalent I following the principle of least astonishment. In general if I have something in memory already, then I use .size, and if my code will generate a request to a database (or external service via an API) I use .count.

– stef | Score: 10

In most cases (e.g. Array or String) size is an alias for length.

count normally comes from Enumerable and can take an optional predicate block. Thus enumerable.count {cond} is [roughly] (enumerable.select {cond}).length -- it can of course bypass the intermediate structure as it just needs the count of matching predicates.

Note: I am not sure if count forces an evaluation of the enumeration if the block is not specified or if it short-circuits to the length if possible.

Edit (and thanks to Mark's answer!): count without a block (at least for Arrays) does not force an evaluation. I suppose without formal behavior it's "open" for other implementations, if forcing an evaluation without a predicate ever even really makes sense anyway.

– user166390 | Score: 7

Rails association not matching camel case class name

Asked by Kirby127 | Score: -2 | Answers: 0

I'm trying to setup an association between my DeviceType class and my VrfEntry class. They were both named with camelCase according to Rails standards. I've setup the belongs_to in the model config for DeviceType. When I go to add a record into the DeviceType it errors out as it is missing the model "Vrfentry" which does not exist. "VrfEntry" exists however.

Device Type Model Config:

class DeviceType < ApplicationRecord
  belongs_to :vrfentry
end

Attempt to create device entry. Fails because it can't find class "Vrfentry" with lowercase e:

catalog(dev):004> DeviceType.create!(device_type: "Anesthesia Machine", category: "MEDICAL", sub_category: "Surgery", vrf_entries_id: 10)

(catalog):4:in '<main>': Missing model class Vrfentry for the DeviceType#vrfentry association. You can specify a different model class with the :class_name option. (NameError)

Rails console showing camelCase "VrfEntry" class name.

catalog(dev):001> VrfEntry.all
  VrfEntry Load (60.2ms)  SELECT "vrf_entries".* FROM "vrf_entries" /* loading for pp */ LIMIT 11 /*application='Catalog'*/
=>
[#<VrfEntry:0x00007f59d8d8c370

How can I do the association in the model to match the camel case of the class?

Proper implementation of using a idempotency key with another service like stripe

Asked by isethi | Score: 3 | Answers: 2

What is the proper way to handle idempotency in a rails application? I am using devise and need to make sure that each user doesn't get multiple duplicate PaymentIntents for the same purchase.

Since the idempotency key needs to be used with each subsequent failed request should it be something saved in the database, session, etc..?

Stripe suggests to use idempotency keys to prevent duplicate PaymentIntents for the same purchase: https://stripe.com/docs/payments/payment-intents#best-practices

Answers:

an idempotency key is any id that helps you and stripe from creating duplicate work.

For example when your user starts to make a Purchase in your application, you want to use the purchase.id as your idempotency key.

Then you would pass that key to stripe for every PurchaseIntent request.

If the customer updates something on the purchase, you would then pass that data along to stripe with the same purchase.id

Once that purchase is complete, you would keep some more data like completed_at:datetime and completed_transaction_data:json

– Blair Anderson | Score: 0

You don't necessarily need to generate/save idempotency keys on your end. Stripe libraries can automatically generate idempotency keys and retry requests with an exponential backoff.

It is important to note that Idempotency keys are useful for preventing double charges in cases of poor network conditions only. They allow for safely retrying requests without accidentally performing the same operation twice. This is useful when an API call is disrupted in transit and you do not receive a response. For example, if a request to create a charge does not respond due to a network connection error, the request can be retried with the same idempotency key to guarantee that no more than one charge is created.

Idempotency keys do not prevent double charges which occur due to a button being pressed twice e.g. maybe a user clicked the button twice while a page was loading and it leads to making two API requests. You would want to use approaches like the disabled HTML attribute to prevent such occurrences.

– alex | Score: 0

rbenv command not found on Mac OS

Asked by Amrmsmb | Score: 1 | Answers: 2

We are trying to run rbenv on El-Capitan 10.11.6. When we try to run rbenv command in the terminal we got the following error message:

command not found

We googled how to solve that issue and one possible solution is to add the "rbenv" to the system PATH, we followed the steps stated in this link. When we run the "$PATH" to check whether or not the rbenv path was added properly into the system PATH, we got the the same result:

command not found

The result of "$PATH" command is:

qwe-Mac-mini:~ amrbakri$ rbenv

-bash: rbenv: command not found
qwe-Mac-mini:~ asd$ echo $PATH    

/Users/asd/.rbenv/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin:/usr/local/MacGPG2/bin

Can you please tell me how to add the path of rbenv properly? And what did I do wrong in the previous steps so that I can fix it.

Answers:

I following the instructions about "bash" command, then do the "eval" operation.

I'm in MacOS 11.2.3, in your .bash_profile, add the two lines.

export PATH="$HOME/.rbenv/bin:$PATH"#this is the required step for my mac

eval "$(rbenv init -)"

refer: https://github.com/rbenv/rbenv#homebrew-on-mac-os-x

– Raymond | Score: 0

rbenv isn't a normal command if you've installed it correctly:

$ type rbenv
rbenv is a function
. . .

According to Homebrew on Mac OS X:

You'll only ever have to run rbenv init once.

That's a bit misleading because the result of running the command is:

$ rbenv init
# Load rbenv automatically by appending
# the following to ~/.bash_profile:

eval "$(rbenv init -)"

So you need to manually add eval "$(rbenv init -)" to some file that bash will source on startup. For most people ~/.bash_profile is the right place.

I notice the commands you listed seem to be run from two different users: amrbakri and asd. Combined with the question's use of "we", I wonder if there might be a problem with the environment being set correctly for one user, but not the other. Can you try using just one user?

If you are running from a non-interactive shell (such as in a crontab), you might need to add eval "$(rbenv init -)" to the startup script.

– Kathryn | Score: 0

bundler: failed to load command: rspec

Asked by Kabanica | Score: 3 | Answers: 1

I am new to Rails and I want to run Rspec using Mac.

When I run:

bundle exec rspec spec/00_hello_spec.rb 

I get the following response:

bundler: failed to load command: rspec (/Users/OumouKaba/Downloads/test-first-ruby-master/vendor/bundle/ruby/2.4.0/bin/rspec)
LoadError: cannot load such file -- spec_helper
  /Users/OumouKaba/Downloads/test-first-ruby-master/vendor/bundle/ruby/2.4.0/gems/rspec-core-3.2.3/lib/rspec/core/configuration.rb:1181:in `require'
  /Users/OumouKaba/Downloads/test-first-ruby-master/vendor/bundle/ruby/2.4.0/gems/rspec-core-3.2.3/lib/rspec/core/configuration.rb:1181:in `block in requires='
  /Users/OumouKaba/Downloads/test-first-ruby-master/vendor/bundle/ruby/2.4.0/gems/rspec-core-3.2.3/lib/rspec/core/configuration.rb:1181:in `each'
  /Users/OumouKaba/Downloads/test-first-ruby-master/vendor/bundle/ruby/2.4.0/gems/rspec-core-3.2.3/lib/rspec/core/configuration.rb:1181:in `requires='
  /Users/OumouKaba/Downloads/test-first-ruby-master/vendor/bundle/ruby/2.4.0/gems/rspec-core-3.2.3/lib/rspec/core/configuration_options.rb:110:in `block in process_options_into'
  /Users/OumouKaba/Downloads/test-first-ruby-master/vendor/bundle/ruby/2.4.0/gems/rspec-core-3.2.3/lib/rspec/core/configuration_options.rb:109:in `each'
  /Users/OumouKaba/Downloads/test-first-ruby-master/vendor/bundle/ruby/2.4.0/gems/rspec-core-3.2.3/lib/rspec/core/configuration_options.rb:109:in `process_options_into'
  /Users/OumouKaba/Downloads/test-first-ruby-master/vendor/bundle/ruby/2.4.0/gems/rspec-core-3.2.3/lib/rspec/core/configuration_options.rb:22:in `configure'
  /Users/OumouKaba/Downloads/test-first-ruby-master/vendor/bundle/ruby/2.4.0/gems/rspec-core-3.2.3/lib/rspec/core/runner.rb:96:in `setup'
  /Users/OumouKaba/Downloads/test-first-ruby-master/vendor/bundle/ruby/2.4.0/gems/rspec-core-3.2.3/lib/rspec/core/runner.rb:85:in `run'
  /Users/OumouKaba/Downloads/test-first-ruby-master/vendor/bundle/ruby/2.4.0/gems/rspec-core-3.2.3/lib/rspec/core/runner.rb:70:in `run'
  /Users/OumouKaba/Downloads/test-first-ruby-master/vendor/bundle/ruby/2.4.0/gems/rspec-core-3.2.3/lib/rspec/core/runner.rb:38:in `invoke'
  /Users/OumouKaba/Downloads/test-first-ruby-master/vendor/bundle/ruby/2.4.0/gems/rspec-core-3.2.3/exe/rspec:4:in `<top (required)>'
  /Users/OumouKaba/Downloads/test-first-ruby-master/vendor/bundle/ruby/2.4.0/bin/rspec:22:in `load'
  /Users/OumouKaba/Downloads/test-first-ruby-master/vendor/bundle/ruby/2.4.0/bin/rspec:22:in `<top (required)>'

Please help with any suggestions or clarification on this issue. To add, I have done this at various level of the file system from root upward. I highly appreciate any clarifications to help me out of my dilemma.

Answers:

If anyone runs into this issue in the future try to see if you have multiple versions of different rspec gems installed, like so:

gem list | grep rspec

In case you do, delete the gem's version that don't match what you have in your Gemfile.lock, like so:

gem uninstall <gem_name> <gem_version>

After following those steps I was able to successfully run rspec spec!

– yagosansz | Score: 0

Count the number of vowels in a text

Asked by Alexandroskw | Score: 1 | Answers: 4

A rookie in Ruby here. I'm trying to count the number of each vowel in a text entered by the user but I'm stuck. My code is this at the moment:

def count_vowels(phrase)
  puts 'Enter a text:'

  phrase = $stdin.gets.downcase.chomp
  a_count = 0
  vowels = ["a", "e", "i", "o", "u"]

  # these two lines are only for debugging
  puts "\nThe text is: #{phrase}"
  puts "#{phrase.chars}"

  for char in vocals
    if char == vocals
      a_count += 1
    end
    return a_count
  end
end

count_vowels(ARGV)

I don't know how to count each vowel:

a = 3

e = 2

and so on.

Answers:

Enumerable#tally is a very cool method that counts occurrences of each value in an array of a hash.

To me, the most idiomatic way to do what you're trying to do is tally the letters in your string, and then slice the vowels.

phrase = 'ruby is a very cool language with a fantastic standard library.'

phrase.chars.tally.slice('a', 'e', 'i', 'o', 'u')

# => {"a"=>9, "e"=>2, "i"=>4, "o"=>2, "u"=>2}

– Richard-Degenne | Score: 0

Use String#count.

def count_vowels(phrase)
  phrase = phrase.downcase

  %w[a e i o u].to_h do |vowel|
    [vowel, phrase.count(vowel)]
  end
end

count_vowels "Every vowel matters"
# => {"a" => 1, "e" => 4, "i" => 0, "o" => 1, "u" => 0}

Also note that in the original attempt at the method, the definition of phrase is getting mixed up by first trying to pass in ARGV (which is an Array, not a String) and then inside the method overwriting phrase using $stdin.gets.

Don't do both. Choose just one technique for getting the technique from the user, and whichever you pick, do it outside the method and just pass in the string.

So, for example:

phrase = ARGV.join " "
count_vowels(phrase)

or

# You don't need to chomp the newline;
# it's not a vowel and won't get counted anyway
phrase = $stdin.gets
count_vowels(phrase)

Once you have the vowel counts in a hash, you can get the count for each vowel individually like so:

my_vowel_count = count_vowels(phrase)

a_count = my_vowel_count["a"]
# => 1

e_count = my_vowel_count["e"]
# => 4

# ...and so on

– user513951 | Score: 1

Some thoughts:

You pass ARGV as an argument to your method but you don't use that passed-in value. Instead, you overwrite phrase right-away.

You have a_count, but where's e_count, i_count and so on?

You have for char in vocals but vocals was never defined before. (maybe a typo?)

When running the above code, you'd get an exception but you didn't mention any exceptions or errors. Do you actually run your code?

What is your method supposed to return? You'd probably say, "the count of each vowel in the text" – but how exactly? Ruby is an object-oriented language. What is the object your method is going to return? Apparently, it can't be a single number.

– Stefan | Score: 0

It looks like you're stuck because you've identified that this is the kind of thing where you iterate over characters, check them, and increment a count, but haven't focused enough on certain details:

  • iterate over characters to count them: Where are the characters that you are counting? Not as a "type", as in vowels or vocals (don't forget to use a consistent name; I know those are synonyms for you but Ruby doesn't). But where do you find the characters multiple times and want to know how many times? That's phrase.
  • if char == vocals — you want to compare a character with the vowels. How do you want to compare it? Well, the character is a vowel if it's the same as one of the elements of vowels. That's not == vocals — equality is a comparison you can make, yes, but you don't want to see if your one character is all of the vowels at once. See this other question: in Ruby, you want .include?
  • If you want a count for each vowel separately, you'll need to do that. You could either have 5 variables and lots of if statements, or better might be to use a hash to map vowel → count.

– Dan Getz | Score: 0

Check if a value exists before updating a column for a already existing record in mysql

Asked by ben | Score: -1 | Answers: 2

Let's say I have a table called Tokens with columns id, refresh_token, and token. refresh_token column should be unique. But we may have many refresh_token fields that are null. These null refresh_token fields should be updated later, but there is a possibility that we may try to enter a refresh_token value that is contained in another field, and that will cause a conflict.

So, what I wanted to do is:

This is how I did it, but I am not sure if it is the best way. Maybe you can advise and give a little explanation about your answer.

    if con.query("(SELECT id FROM Tokens WHERE refresh_token='#{refresh_token}') LIMIT 1;").count == 1
       # do something important here
    else
        con.query("UPDATE Tokens SET refresh_token='#{refresh_token}' WHERE id='#{id}';")
    end

this is done using ruby.

Answers:

You can perform the update like this:

UPDATE Tokens
SET refresh_token = 'C08Rbs'
WHERE id = '2'
AND NOT EXISTS (SELECT refresh_token FROM Tokens WHERE refresh_token = 'C08Rbs')

Use ROW_COUNT() to determine if any rows were actually updated. Assuming the row where id = 2 actually exists, it will return 0 if no rows were updated (because the value already exists).

The ROW_COUNT() function is also provided in the MySQL API (as mysql_affected_rows()), so your programming language of choice will have a function to return the same thing, and generally the result of an UPDATE will return the number of affected rows.

Normally, you use a unique index to avoid duplicates on a particular column or columns and simply try to update:

UPDATE IGNORE Tokens
SET refresh_token = 'C08Rbs'
WHERE id = 2

Using IGNORE keeps you from getting an error on a duplicate value, the update won't occur, and it will still return the number of rows actually updated. It will return 1 on success and 0 on failure.

It's still strange that you're changing a "NULL" value rather than inserting a new record.

You haven't said what you want to do if the value already exists.

– Marcus Adams | Score: 0

You can use the following statements to perform a check before updating.

IF (NOT EXISTS(SELECT * FROM Tokens WHERE Token = ''))  
    BEGIN 
        INSERT INTO Tokens(token,..,..) 
        VALUES(val1,val2,val3) 
    END 
    END

OR

  IF (EXISTS(SELECT * FROM Tokens WHERE Token = ''))  
        BEGIN 
            update Tokens
           SET token = myVal
        END 
        END

Not sure what you need. Hope any one of the above helps you :)

– Nitin Alapati | Score: -1

ruby selenium click on button with class name

Asked by xxd | Score: 1 | Answers: 2

I'm using ruby and selenium to test a web page, with the two buttons below

<div class="AVdis">
  <span class="gwt-InlineHTML"/>
    <a class="AVcur" name="attendEdit"; font-size: 12px;">[edit]</a>
</div>
<div class="lineHeight">
  <button type="button" class="pcbtn" style="display: inline-block;">yes</button>
</div>

I've tried to use

driver.find_elements(:class, 'AVcur').click 
driver.find_elements(:class, 'pcbtn').click 

but it doesn't work, please advise.

Thanks

updated the full HTML code(the part code of class 'pcbtn' ONLY, it doesn't include the part with class 'AVcur'.):

<body>
  <iframe src="javascript:'';" id="__gwt_historyFrame" style="width: 0px; height: 0px; border: 0px; display: block;"/>
  <iframe src="javascript:''" id="Attend" tabindex="-1" style="position: absolute; width: 0px; height: 0px; border: none;"/>
  <div style="display: none;"/>
    <div class="GFKFO5SBPF hBody nClientFalse">
      <div class="left" style="width: 198px;">
        <div class="contents nClientFalse2">
          <div class="AVright">
            <div class="GFKFO5SBIQ">
              <div class="AVfirstTd">
                <table cellspacing="0" cellpadding="0">
                  <tbody>
                    <tr>
                      <td align="left" style="vertical-align: top;">
                        <div>
                          <table cellpadding="0" cellspacing="0" class="pcattd_record" width="630px">
                            <tbody>
                              <tr class="GFKFO5SBCS">
                                <tr class="GFKFO5SBCS">
                                  <th>
                                    <td>
                                      <table class="noborder">
                                        <tbody>
                                          <tr>
                                            <td>
                                            <td>
                                              <div class="lineHeight">
                                                <button type="button" class="pcbtn" style="display: inline-block;">press button</button>
Answers:

Click an element:

driver.find_element(css: 'a').click

– Dorian | Score: 0

Try to click it, using xpath:

driver.find_element(:xpath, "//div[@class='AVdis']//a[@name='attendEdit']").click

Second element xpath:

driver.find_element(:xpath, "//div[@class='lineHeight']//button[@class='pcbtn'][text()='yes']").click

– German Petrov | Score: 0

RSpec Mock - class does not implement the instance method: jql. Perhaps you meant to use `class_double` instead?

Asked by mr_muscle | Score: 4 | Answers: 1

I want to mock method which use Jira-Ruby gem with jql lib

def call
  client = JIRA::Client.new(options)
  client.Issue.jql(
    "project = #{project_key} AND
    status != Done AND
    status != Closed AND
    status != Cancelled AND
    status != Followup",
    query_options
  )
end

my mock:

  let(:jql_options) do
    [
      "project = TSW-123 AND
      status != Done AND
      status != Closed AND
      status != Cancelled AND
      status != Followup",
      query_options
    ]
  end
  let(:query_options) do
    {
      start_at: 0,
      max_results: 1000
    }
  end
  let(:jira_client) { instance_double(JIRA::Client) }
  let(:issue) { instance_double(JIRA::Resource::Issue) }
  let(:issue_factory) { instance_double(JIRA::Resource::Issue) }

  before do
    allow(JIRA::Client).to receive(:new).with(options).and_return(jira_client)
    allow(jira_client).to receive(:Issue).and_return(issue_factory)
    allow(issue_factory).to receive(:jql).with(*jql_options).and_return(issue)
  end

  it 'connect to the project' do
    expect(subject.call).to eq(project)
  end

I'm getting an error:

JIRA::Resource::Issue class does not implement the instance method: jql. Perhaps you meant to use class_double instead?

Answers:

A few things:

  • You're using mocking syntax for static values, not objects. My answer to your other question here should help: https://stackoverflow.com/a/60404227/4024628 IMO, the use of instance_double here is fine because you are mocking instances, though if you are going to call the mocked object's methods you often need to define their responses in the instance_double declaration (as mentioned in my linked comment).
  • Be careful with testing mocked behavior; you should only need to test that the client object is created with certain options, and that jql is called with specific args (meaning, make sure you're validating your code's behavior against breaking changes -- not the gem's behavior).
  • Your spec is testing that call returns project, but you haven't defined or mocked that anywhere?
  • You are also defining issue_factory and issue as instance_doubles of the same class, which is inconsistent with the documentation for the classes you're using (typo?).

Something like this might be sufficient:

# You should always name your subject if you are calling methods on it
subject(:instance) { described_class.new }

let(:client)        { instance_double(JIRA::Client)
let(:issue_factory) { instance_double(JIRA::Resource::IssueFactory) }
# This likely needs to be an OpenStruct instead since docu says it returns an obj
let(:project)       { instance_double(JIRA::Resource::Project) }

before do 
  allow(client).to receive(:new).with(options)  { client }
  allow(client).to receive(:Issue) { issue_factory }
  allow(issue_factory).to receive(:jql).with(*jql_options) { project }
end

it 'creates client with correct options' do 
  expect(client).to receive(:new).with(options) 
  instance.call
end

it 'calls #jql with correct options' do
  expect(issue_factory).to receive(:jql).with(*jql_options)
  instance.call
end

it { expect(instance.call).to eq(project) }

– Allison | Score: 0

Simultaneously creating instance and class methods with the same name in a ruby class

Asked by Zee | Score: 8 | Answers: 2

Is there a way for me to simultaneously create a class and an instance method in a ruby class that have the same name? I have a version of this created in the class Foo

class Foo 
   def self.bar
      "hello world" 
   end

   def bar
     self.class.bar
   end
end

While this works, is there a more elegant way of achieving this? Right now, I would have to duplicate ~10 methods as instance and class methods.

Answers:

Since this is also tagged as ruby-on-rails, in case someone comes back to this post.

delegate :bar, to: :class

Should also achieve what you need.

– Toby Osbourn | Score: 0

you can use Ruby's Forwardable like this:

# in foo.rb
class Foo
  extend Forwardable

  def_delegators :Foo, :bar, :baz, :qux

  def self.bar
    "hello bar"
  end

end

then

> Foo.bar #=> "hello bar"
> Foo.new.bar #=> "hello bar"

You can also use method_missing like this:

class Foo
  DelegatedMethods = %i[bar baz qux]

  def method_missing(method)
    if DelegatedMethods.include? method
      self.class.send method
    else
      super
    end
  end

  def self.bar
    "a man walked into a bar"
  end
end

– Les Nightingill | Score: 4

Using Named Captures with regex match in Ruby&#39;s case...when?

Asked by Chris | Score: 16 | Answers: 2

I want to parse user input using named captures for readability.

When they type a command I want to capture some params and pass them. I'm using RegExps in a case statement and thus I can't assign the return of /pattern/.named_captures.

Here is what I would like to be able to do (for example):

while command != "quit"
  print "Command: "
  command = gets.chomp
  case command
  when /load (?<filename>\w+)/
    load(filename)
  end
end
Answers:

Named captures set local variables when this syntax.

regex-literal =~ string

Doesn't set in other syntax. # See rdoc(re.c)

regex-variable =~ string

string =~ regex

regex.match(string)

case string
when regex
else
end

I like named captures too, but I don't like this behavior. Now, we have to use $~ in case syntax.

case string
when /(?<name>.)/
  $~[:name]
else
end

– kachick | Score: 19

This is ugly but works for me in Ruby 1.9.3:

while command != "quit"
  print "Command: "
  command = gets.chomp
  case command
  when /load (?<filename>\w+)/
    load($~[:filename])
  end
end

Alternatively you can use the English extension of $~, $LAST_MATCH_INFO.

– Gabe Kopley | Score: 9

Rails environment how to find out in code?

Asked by Felix | Score: 1 | Answers: 2

Are there any solutions how I can find out in which environment my application is running?

I have some rake calls which need to have the environment like this:

system "RAILS_ENV=development rake crons:dosomething"

But this should not only work in development I want to use this in test production and development?

how can I do this?

second task where I need this is in config/schedule.rb the should also run in all environments

rake "crons:dosomething", :environment => :development
rake "crons:dosomething", :environment => :production

this doesn't work

Answers:

You can also do

Rails.env.production? || Rails.env.development?

with any of the environments you have.

Alternatively to pass an environment to a rake task you can do this

rake "crons:dosomething RAILS_ENV=production"

– dandlezzz | Score: 2

You can match it to strings like:

if Rails.env.eql?('production')
  #Do production things
end 

– errata | Score: 1

Ruby native extensions fail to build after macOS upgrade

Asked by David | Score: 1 | Answers: 2

After upgrading to macOS Golden Gate 27.0.1, my Jekyll-based website stopped working because Bundler cannot find several required gems.

Ruby and Bundler versions

ruby 4.0.9 (2026-10-23 revision 3e93b23afc) +PRISM [arm64-darwin27]
Bundler version 4.0.11

Missing gems

Running bundle list reports:

Could not find eventmachine-1.2.7, http_parser.rb-0.8.1,
bigdecimal-4.1.2 in locally installed gems.

Running bundle install fails when attempting to build native extensions. For example, the build of bigdecimal produces the following error:

Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

current directory:
/opt/homebrew/lib/ruby/gems/4.0.0/gems/bigdecimal-4.1.2/ext/bigdecimal

/opt/homebrew/opt/ruby/bin/ruby extconf.rb

checking for __builtin_clz()... *** extconf.rb failed ***

Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers. Check the mkmf.log file for more details.

The compiler failed to generate an executable file.
(RuntimeError)

You have to install development tools first.

The build log is located at:

/opt/homebrew/lib/ruby/gems/4.0.0/extensions/arm64-darwin-27/4.0.0/bigdecimal-4.1.2/mkmf.log

The relevant excerpt from mkmf.log appears incomplete, so I have not included it here.

Command Line Tools

I have not installed the full Xcode application, but the Command Line Tools are installed, with a reported version of 27.0.0.0.

Software Update repeatedly attempts to install the Command Line Tools. I deleted the existing installation and allowed Software Update to reinstall it, but the update cycle continues.

Questions

  1. What could cause Ruby's native extensions to fail to compile when the Command Line Tools are apparently installed?

  2. How can I determine whether the problem lies with the compiler, SDK configuration, or Ruby installation?

  3. Could the repeated Command Line Tools update attempts be related to the compilation failure, and how can I diagnose this?

I would be grateful for any help or suggestions on how to resolve this.

Answers:

Thanks for all of the suggestions.

The problem with the CLT repeatedly looping through its installation disappeared when the next version of macOS, Golden Gate, was installed. It is now version 27.2.

I eventually tracked down the errors to the CLT version of clang. In general, there appeared to be conflicts between various development tools installed via Homebrew and those provided by the CLT. I therefore installed llvm using Homebrew:

brew install llvm

I also modified the environment for the interactive shell to make sure that everything was pointing to the Homebrew directories:

if [ -d "/opt/homebrew/opt/ruby/bin" ]; then
  export PATH=/opt/homebrew/opt/ruby/bin:$PATH
  export PATH=`gem environment gemdir`/bin:$PATH
fi

export PATH="/opt/homebrew/bin:$PATH"

# LLVM installed by Homebrew

export PATH="/opt/homebrew/opt/llvm/bin:$PATH"

export LDFLAGS=-L/opt/homebrew/opt/llvm/lib

export CPPFLAGS=-I/opt/homebrew/opt/llvm/include

export CMAKE_PREFIX_PATH=/opt/homebrew/opt/llvm

After making these changes, the native extensions for the gems compiled successfully and were installed.

– David | Score: 1

Did you accept the license after installing the developer tools?

You can accept it with this command:

$ sudo xcodebuild -license

– spickermann | Score: 2

How do I know which types are expected? Where do I get that information from?

Asked by cluster1 | Score: -3 | Answers: 1

Let's say I've got this class:

class Person
  attr_accessor :first_name, :last_name, :email, :projects

  def initialize(first_name:, last_name:, email:, projects:)
    @first_name = first_name
    @last_name = last_name
    @email = email
    @projects = projects
  end
end

How would someone who wants to create a Person object know which arguments have to be passed?

The first three arguments one could guess that it’s a string. But with the fourth argument it is completely unobvious.

Could be comma-separated string, IDs, could be an array, dictionary, etc. And what structure does the array have? Does it contain strings or project objects?

The same with methods. How do I know which type is returned?

In something like C#/Visual Studio I can hover over the method and get this information.

How do these things work in Ruby? Where does a professional Ruby developer get this information from? How do they handle a task like described above with creating the object?

Answers:

Search the codebase for Person.new to see how other developers instantiated it.

Look for a Project class in the codebase. If it exists, projects: almost certainly expects an array of those objects.

Run the code in a REPL (IRB/Pry) or a test to see what method calls fail if they pass a dummy string versus an array.

– joe | Score: 1

Does Ruby support type-hinting?

Asked by NONE | Score: 20 | Answers: 5

PHP example:

function do_something(int $i) {
    return $i + 2;
}

Ruby example:

class MyClass
    # ...
end

def do_something(MyClass x)
    x.prop1 = "String..."
end

Is there anything similar to this?

Answers:

Ruby 3 will introduce types to Ruby (Source). You can already use Sorbet now to add types to your ruby code.

– jayeff | Score: 16

Shameless plug - I just published a ruby gem for this - http://rubygems.org/gems/type_hinting

Usage is here - https://github.com/beezee/ruby_type_hinting

I went looking for it first and found this thread. Couldn't find what I was looking for so I wrote it and figured I'd share here.

I think it's more concise than any of the proposed solutions here and also allows you to specify return type for a method.

– Brian Zeligson | Score: 5

No, Ruby itself doesn't support it, and I think that isn't the intention of Matz to add it to the language... Ruby really embraces duck typing in its own internal API and it makes Ruby a very dynamic and productive language...

– kelvinst | Score: 1

Ruby does not have such thing, but all you have to do is add a single line as so:

def do_something(x)
  raise "Argument error blah blah" unless x.kind_of?(MyClass)
  ...
end

Not a big deal. But if you feel it is too verbose, then just define a method:

module Kernel
  def verify klass, arg
    raise "Argument error blah blah" unless arg.kind_of?(klass)
  end
end

and put that in the first line:

def do_something(x)
  verify(MyClass, x)
  ...
end

– sawa | Score: 9

If you really want to make sure a certain action is performed on an instance of a specific class (like an integer), then consider defining that action on the specific class:

class Integer
  def two_more
    self + 2
  end
end

3.two_more   #=> 5
2.0.two_more #=> undefined method `two_more' for 2.0:Float (NoMethodError)

class MyClass
  def do_something
     self.prop1 = "String..."
  end
end

– steenslag | Score: 3

How to set the request.body for an Rspec request spec with a GET request

Asked by Apie | Score: 12 | Answers: 2

I have inherited a code base. I am busy writing integration tests to tie down the app functionality before I consider refactoring.

I have the following lines in a controller concern before_action. It seems to read the request body. The json value here is used to extract an identifier used to authenticate the request.

request.body.rewind
body = request.body.read
json = JSON.parse(body) unless body.empty?

I need to test that the authentication happens correctly. How can I set the request.body for a GET request spec?

Answers:

@rails_post_5

require "rails_helper"

RSpec.describe "Widget management", :type => :request do

  it "creates a Widget and redirects to the Widget's page" do
  headers = { "CONTENT_TYPE" => "application/json" }
  post "/widgets", :params => '{ "widget": { "name":"My Widget" } }', :headers => headers
    expect(response).to redirect_to(assigns(:widget))
  end

end

or just

post "/widgets", params: '{ "widget": { "name":"My Widget" } }'

– Atsushi Takayama | Score: 4

I think you should be able to do this via the request env RAW_POST_DATA

get root_path, {}, 'RAW_POST_DATA' => 'raw json string'
request.raw_post # "raw json string"

See: How to send raw post data in a Rails functional test?

– hajpoj | Score: 7

Can we access the objects we created in ruby using their object _ids in ruby?

Asked by Praveen Dhawan | Score: 1 | Answers: 2

How are the object IDs assigned in Ruby? Do some objects have fixed object_id? Can we access them using their object _ids?

Answers:

How an object ID is “assigned” depends on the Ruby implementation and other factors like the OS bitness. For example, in CRuby nil.object_id returns 4 on 32-bit and 8 on 64-bit.

Additionally nil is a so called immediate value. true, false, fixnums (small integers) and sometimes even floats are other immediate values. They have fixed IDs for the following reasons:

  • they're passed by value and not by reference like the other (dynamically allocated) objects
  • there's only one nil, one true, one 19, etc. however there can be two different arrays

See the documentation of BasicObject#__id__. You can also click to toggle the source to get a look at the CRuby implementation.

Call ObjectSpace._id2ref to retrieve an object by ID:

id = nil.object_id
ObjectSpace._id2ref(id) # => nil

In some implementations that method may not be implemented or really slow. According to matz it was originally a hack needed to implement weakref but current versions don't call it anymore.

– cremno | Score: 5

How are the object IDs assigned in Ruby?

The Ruby Language Specification doesn't say anything about how IDs are assigned, only that

  • an object has to have the same ID over its lifetime
  • no two objects can have the same ID at the same time

Note that this doesn't prohibit that two different objects may have the same ID at different times, i.e. it is allowed to reuse IDs.

Do some objects have fixed object_id?

The Ruby Language Specification doesn't say anything about how IDs are assigned. On some Ruby Implementations some objects may or may not have fixed IDs.

Can we access them using their object _ids?

On some implementations, there is a method called ObjectSpace::_id2ref, but this method is not guaranteed to exist on all implementations, and it may be really expensive and on some implementations must be explicitly enabled with a command line switch.

– J&#246;rg W Mittag | Score: 1

Stripe error while creating customer: You passed an empty string for &#39;card&#39;

Asked by user3597950 | Score: 3 | Answers: 3

Stripe will not accept payments, the charge keeps failing. I am getting this error:

Started POST "/charges" for 127.0.0.1 at 2014-06-09 06:30:58 -0700
Processing by ChargesController#create as HTML
  Parameters: {"utf8"=>"√", "authenticity_token"=>"9bqk2Q6NEM1ehHDJPgncNQ3gnP0X1hQK6y6ENm3Yb1g=", "c
harge"=>{"contest_id"=>"36", "user_id"=>"", "amount"=>"12", "stripe_card_token"=>""}, "card_number"=
>"4242 4242 4242 4242", "card_code"=>"478", "button"=>""}
Stripe error while creating customer: You passed an empty string for 'card'. We assume empty values
are an attempt to unset a parameter; however 'card' cannot be unset. You should remove 'card' from y
our request or supply a non-empty value
Redirected to http://localhost:3000/
Completed 302 Found in 477ms (ActiveRecord: 0.0ms)

It seems as if it might not be creating the stripe token? What is going on here?

This is my form:

 <% content_for :head do %>
        <%= tag :meta, :name => "stripe-key", :content => STRIPE_PUBLIC_KEY %>
    <% end %>
    <%= form_for @charge, :html => { :class => 'form' } do |f| %>
        <div class="form-inputs">
            <div class="row">
                <%= f.hidden_field :contest_id, value: @contest.id  %>
                <%= f.hidden_field :user_id %>
                <%= f.hidden_field :amount %>
                <!-- TODO CHANGE THIS ACCORDINGLY  -->
                <%= f.hidden_field :stripe_card_token %>
                <div class="small-12 medium-6 large-2 columns">
                    <%= f.label "Amount:", class: "text-right" %>
                </div>
                <div class="small-12 medium-6 large-10 columns" style="margin-bottom: 0.5rem; margin-top: 0.5rem;">
                    <%= number_to_currency(@charge.amount, :unit => "$") %>
                </div>
                <% if @charge.stripe_card_token.present? %>
                  Credit card has been provided.
                <% else %>
                  <div class="small-12 medium-6 large-2 columns">
                    <%= label_tag :card_number, "Credit Card Number:", class: "text-right" %>
                  </div>
                  <div class="small-12 medium-6 large-10 columns">
                    <%= text_field_tag :card_number %>
                  </div>
                  <div class="small-12 medium-6 large-2 columns">
                    <%= label_tag :card_code, "Security Code on Card (CVV):", class: "text-right" %>
                  </div>
                  <div class="small-12 medium-6 large-10 columns end">
                    <%= text_field_tag :card_code %>
                  </div>
                  <div class="small-12 medium-6 large-2 columns">
                    <%= label_tag :card_month, "Card Expiration:", class: "text-right" %>
                  </div>
                  <div class="small-6 medium-3 columns">
                    <%= select_month nil, {add_month_numbers: true}, {name: nil, id: "card_month"} %>
                  </div>
                  <div class="small-6 medium-3 columns">
                    <%= select_year nil, {start_year: Date.today.year, end_year: Date.today.year+15}, {name: nil, id: "card_year"} %>
                  </div>
                <% end %>
                <div id="stripe_error">
                  <noscript>JavaScript is not enabled and is required for this form. First enable it in your web browser settings.</noscript>
                </div>

            </div>
            <div class="row">
                <div class="form-actions small-9 small-offset-2 columns">
                    <%= button_tag :type => "button", :class => "radius" do  %>
                        <%= link_to "Back", @contest, :style => "color: white" %>
                    <% end %>
                    <%= f.button :Donate, :class => "radius" %>
                </div>
            </div>
        </div>
    <% end %>
    <% content_for :js do %>
        <%= javascript_include_tag "https://js.stripe.com/v1", "application" %> 
        <%= javascript_include_tag asset_path("stripe/stripe.js"), "application" %>
    <% end %>

This is my charges controller:

class ChargesController < ApplicationController

    def new
      @contest = Contest.find(params[:id])
      @charge = Charge.new(amount: params[:amount])
    end

    def create
      @charge = Charge.new(charges_params)
      if @charge.save_with_payment(@charge)
        redirect_to root_path, :notice => "Contribution was recorded succesfully!"
      else
        redirect_to root_path, :notice => "Transaction was not able to be recorded"
      end
    end

    def charges_params
        params.require(:charge).permit(:stripe_card_token, :contest_id, :user_id, :amount)
    end

end

My Charge Model:

class Charge < ActiveRecord::Base

    attr_accessor :stripe_card_token

    belongs_to :contest
    belongs_to :user

    def save_with_payment(charge)
      if valid?
        Stripe::Charge.create(
          :amount => (charge.amount.to_i)*100,
          :currency => "usd",
          :card => stripe_card_token);
        save
      end
    rescue Stripe::InvalidRequestError => e
      logger.error "Stripe error while creating customer: #{e.message}"
      errors.add :base, "There was a problem with your credit card."
      false
    end

end
Answers:

I encountered the same problem.
my subscription.js.coffee:

jQuery ->
  Stripe.setPublishableKey($('meta[name="stripe-key"]').attr('content'))
  subscription.setupForm()

subscription =
  setupForm: ->
    $('#new_subscription').submit (e) ->
      $('input[type=submit]').attr('disabled', true)
      subscription.processCard()
      return false

  processCard: ->
    card =
      number: $('#card_number').val()
      cvc: $('#card_code').val()
      expMonth: $('#card_month').val()
      expYear: $('#card_year').val()
    Stripe.createToken(card, subscription.handleStripeResponse)

  handleStripeResponse: (status, response) ->
    if status == 200
      $('#subscription_stripe_card_token').val(response.id)
      $('#new_subscription')[0].submit()
    else
      $('#stripe_error').text(response.error.message) 
      $('input[type=submit]').attr('disabled', false)
      false

As you can see when user pushes submit button the function $('#new_subscription').submit (e) is raised. There is almost all of the stripe magic in the submit function.

In my case sometimes the submit function is not raised therefore empty stripe_card_toke parameter is sent to your server.

The strange behavior is caused by Rails turbolinks facilities.
I solved it in such way:

  1. Add to Gemfile a line:
    gem 'jquery-turbolinks'
  2. Add to manifest application.js a line:
    //= require jquery.turbolinks
    So my application.js looks like:
//= require jquery
//= require jquery.turbolinks
//= require jquery_ujs
//= require turbolinks
//= require bootstrap
//= require jquery_nested_form
//= require_tree .

– Lesha Pipiev | Score: -1

Unrelated to stripe_card_token being blank, your server is currently in PCI scope because it's receiving the card number and CVV code. This is probably not what you're intending if you're using Stripe.

From the Stripe Getting Started docs:

Note how input fields representing sensitive card data (number, CVC, expiration month and year) do not have a "name" attribute. This prevents them from hitting your server when the form is submitted.

Rails tag helpers generate a name attribute by default. That's not desirable in this case.

You can override this behavior by passing nil for both name and value, and defining an identifier of some kind:

<%= text_field_tag nil, nil, 'data-stripe' => 'card_number' %>

Here I've used Stripe's currently-recommended data-stripe, but you can just as well use the id attribute (as their older tutorials recommended).

Getting back to your original question, the problem is in your Charge model, where you're overriding Active Record and masking the data in the database:

class Charge < ActiveRecord::Base

    attr_accessor :stripe_card_token     # Don't do this!

attr_accessor should never be used on database columns. Active Record provides its own accessors in order to pull that data from the database; by declaring an accessor here, you're replacing Active Record's functionality with Ruby's base functionality:

irb(main):001:0> Charge.first
  Charge Load (0.3ms)  SELECT  "charges".* FROM "charges"   ORDER BY "charges"."id" ASC LIMIT 1
=> #<Charge id: 1, stripe_card_token: "0xdeadbeef", created_at: "2014-06-11 14:27:40", updated_at: "2014-06-11 14:27:40">
irb(main):002:0> c.stripe_card_token
=> nil

That being said, the Railscast you started from is nearly three years old, violates best practices all over the place, and uses a long-outdated API endpoint. Once you correct your model, you're still better off starting your form and JavaScript over using Stripe's current tutorial and documentation.

– colinm | Score: 0

Most likely it looks like stripe_card_token is blank as its

:card => stripe_card_token

try and change that to

:card => charge.stripe_card_token

– emcanes | Score: 0

How to return all Dataset by Sequel query

Asked by ironsand | Score: 0 | Answers: 1

Rails scope returns all(ActiveRecord::Relation) instead of nil. So that I can use method chain when condition is nil.

class MyClass < ApplicationRecord
  scope :my_filter, ->(condition) { where(condition: condition) if condition.present? }
end

MyClass.where(foo: 'foo').my_filter(condition).order(:date)

I want to implement similar functionality in Sequel, but this code doesn't work well because all in Sequel returns an Array. How can I write a functionality in Sequel similar to Rails scope?

class MyClass < Sequel::Model
  dataset_module do
    def my_filter(condition)
      return all if condition.nil?
      where(condition: condition) 
    end
  end
end
Answers:

Since where returns a Dataset I am assuming you would also like "all" to return the same object.

As you have identified all will return an Array; however you can retrieve the Dataset by using either clone or self

So we can just change your implementation to:

class MyClass < Sequel::Model
  dataset_module do
    def my_filter(condition)
      return clone if condition.nil?
      where(condition: condition) 
    end
  end
end

Working Example: https://replit.com/@engineersmnky/SequelGemRailsScope#main.rb

Additional Info:

I chose clone because most query methods utilize this method (similar to spawn in ActiveRecord).

Dataset#clone looks like this

def clone(opts = nil || (return self))
  c = super(:freeze=>false)
  c.opts.merge!(opts)
  unless opts.each_key{|o| break if COLUMN_CHANGE_OPTS.include?(o)}
    c.clear_columns_cache
  end
  c.freeze
end

clone's method signature shortcuts execution if no condition is passed and simply returns self.

As stated in the comments

return self used above because clone is called by almost all other query methods, and it is the fastest approach

However the comments do also state

This method should generally not be called directly by user code.

So you could choose to just use return self instead.*

*I implemented both options in my Example above to show their identical functionality plus that method signature is pretty interesting

– engineersmnky | Score: 1

is it OK to use begin/end in Ruby the way I would use #region in C#?

Asked by Simon | Score: 5 | Answers: 5

I've recently moved from C# to Ruby, and I find myself missing the ability to make collapsible, labelled regions of code. It just occurred to me that it ought to be OK to do this sort of thing:

class Example
  begin # a group of methods

    def method1
      ..
    end

    def method2
      ..
    end

  end

  def method3
    ..
  end
end

...but is it actually OK to do that? Do method1 and method2 end up being the same kind of thing as method3? Or is there some Ruby idiom for doing this that I haven't seen yet?

Answers:

I know this might be a bit old but I ran into this issue and found a killer solution. If you're using "Rubymine" you can do #regions.

This is where they talk about navigating regions https://www.jetbrains.com/ruby/help/navigating-to-custom-region.html

#region Description 
Your code goes here... 
#endregion

So with the above in your code you will see the below:

Rubymine code editor - With a sample method using regions un-folded Rubymine code editor - With a sample method using regions **un-folded**.

Rubymine code editor - With a sample method using regions folded Rubymine code editor - With a sample method using **regions** folded.

– JamesDeHart | Score: 4

As others have said this doesn't change the method definition.

However, if you want to label groups of methods, why not use Ruby semantics to label them? You could use modules to split your code into chunks that belong together. This is good practice for large classes, even if you don't reuse the modules. When the code grows, it will be easy to split the modules into separate files for better organisation.

class Example
  module ExampleGroup
    def method1
      # ..
    end

    def method2
      # ..
    end
  end
  include ExampleGroup

  def method3
    # ..
  end
end

– molf | Score: 7

Adding arbitrary Ruby code in order to please your editor doesn't seem reasonable to me at all. I think you should try to get a decent text editor, one that would be able to configure to use some keyword you put in your comments to enable code folding there, for example:

# region start AAA

some(:code, :here)

# region end AAA

And if you allow me to be sarcastic: you should know that Ruby is lot more expressive, elegant and pretty than C#, and chances are that there isn't any Ruby code ought to be hidden in the first place! ;)

– Mladen Jablanović | Score: 6

I think it should be OK. I haven't seen it a lot though. Another way you could accomplish the same thing, while using less indentation, is to close and reopen the class, like so:

class Example
  def method1
    ..
  end

  def method2
    ..
  end
end

# optionally put some other code here

class Example
  def method3
    ..
  end
end

I think this is often used so that you can put other code in the middle, such as when there's a constant defined in the first class Example block, which is used to define a constant in the middle code, which is used to define a constant in the second class Example block. That way you never have to refer to a constant before it's defined.

– wdebeaum | Score: 2

Yes, it is okay to do that (i.e. it doesn't change the semantics of your code).

However this isn't a common pattern and it might be confusing to readers of your code who wouldn't understand what the purpose of the begin ... end block is.

– sepp2k | Score: 2

Simple spell check method/gem in ruby?

Asked by TaylorT | Score: 10 | Answers: 3

I am looking for a relatively quick way to check whether words are misspelled, either using a gem or API.

I've tried using several gems -- raspell, ffi-aspell, hunspell-ffi, spell_cheker, and spellchecker -- and each has a different error.

I'm pretty new to ruby and hoping for a simple solution (I'm processing a lot of short text files and want to calculate the % of words mis-spelled) that doesn't include building something from scratch.

When trying ffi-aspell, I get the following error:

/Users/ntaylorthompson/.rvm/gems/ruby-1.9.2-p320/gems/ffi-aspell-0.0.3/lib/ffi/aspell/speller.rb:121: [BUG] Segmentation fault
ruby 1.9.2p320 (2012-04-20 revision 35421) [x86_64-darwin11.4.0]

-- control frame ----------
c:0005 p:---- s:0019 b:0019 l:000018 d:000018 CFUNC  :speller_check
c:0004 p:0113 s:0013 b:0013 l:000012 d:000012 METHOD /Users/ntaylorthompson/.rvm/gems/ruby-1.9.2-p320/gems/ffi-aspell-0.0.3/lib/ffi/aspell/speller.rb:121
c:0003 p:0049 s:0007 b:0007 l:0005a8 d:0005d0 EVAL   ffi-aspell_test.rb:5
c:0002 p:---- s:0004 b:0004 l:000003 d:000003 FINISH
c:0001 p:0000 s:0002 b:0002 l:0005a8 d:0005a8 TOP   
---------------------------
-- Ruby level backtrace information ----------------------------------------
ffi-aspell_test.rb:5:in `<main>'
/Users/ntaylorthompson/.rvm/gems/ruby-1.9.2-p320/gems/ffi-aspell-0.0.3/lib/ffi/aspell/speller.rb:121:in `correct?'
/Users/ntaylorthompson/.rvm/gems/ruby-1.9.2-p320/gems/ffi-aspell-0.0.3/lib/ffi/aspell/speller.rb:121:in `speller_check'

-- C level backtrace information -------------------------------------------

[NOTE]
You may have encountered a bug in the Ruby interpreter or extension libraries.
Bug reports are welcome.
For details: http://www.ruby-lang.org/bugreport.html

Abort trap: 6

I'd appreciate either (1) a suggestion of an alternative approach to those above or (2) a recommendation of which to use of the 5 gems above -- so I can at least spend time debugging the best option.

Answers:

I made https://github.com/dblock/rubocop-spellcheck.

It checks spelling in Ruby comments, strings, identifiers, Markdown, RDoc, AsciiDoc and plain text. About 20x faster than PySpell.

– dB. | Score: 1

As jmdeldin said raspell is no longer maintained, ffi-aspell is a fork of it.

I played few minutes with it and it's quite easy to use:

  1. Instantiates an FFI::Aspell::Speller object specifying the language
  2. Check if a word is correct using speller.correct?(word)
  3. Get a list of suggestions for a word using speller.suggestions(word)

NOTE: The bigger limitation I've found so far is that the interface of the speller works on words only. If you want to spell check a whole document you'll need to split it in words. This could not be trivial, especially if you have an HTML input...

(It depends on aspell of course so you need to install it using brew install aspell or your preferred package manager)

– Aldo &#39;xoen&#39; Giambelluca | Score: 0

raspell is no longer maintained, so ffi-aspell is a good option if you have the libaspell headers available.

If you can't get the libraries to work, you can just shell out to the aspell binary. The following method will do just that (unit tests included):

# Returns the percentage of incorrect words per document
#
def spellcheck(filename)
  fail "File #{filename} does not exist" unless File.exists?(filename)

  words = Float(`wc -w #{filename}`.split.first)
  wrong = Float(`cat #{filename} | aspell --list | wc -l`.split.first)

  wrong / words
end

if $0 == __FILE__
  require 'minitest/autorun'
  require 'tempfile'

  describe :spellcheck do
    def write(str)
      @file.write str
      @file.read
    end

    before do
      @file = Tempfile.new('document')
    end

    it 'fails when given a bad path' do
      -> { spellcheck('/tmp/does/not/exist') }.must_raise RuntimeError
    end

    it 'returns 0.0 if there are no misspellings' do
      write 'The quick brown fox'
      spellcheck(@file.path).must_equal 0.0
    end

    it 'returns 0.5 if 2/4 words are misspelled' do
      write 'jumped over da lacie'
      spellcheck(@file.path).must_be_close_to 0.5, 1e-8
    end

    it 'returns 1.0 if everything is misspelled' do
      write 'Da quyck bown foxx jmped oer da lassy dogg'
      spellcheck(@file.path).must_equal 1.0, 1e-8
    end

    after do
      @file.close
      @file.unlink
    end
  end
end

spellcheck() assumes you have cat, wc, and aspell on your path, and that the default dictionary is what you want to use. The unit test is for Ruby 1.9 only -- if you're running 1.8, just delete it.

– jmdeldin | Score: 7

How to use TLS 1.2 in Ruby Http client

Asked by loganathan | Score: 3 | Answers: 1

I'm trying to access third party api using TLS 1.2, but getting SSL error event with valid certificates

Ruby Version:

 ruby 2.3.0p0 (2015-12-25 revision 53290) [x86_64-linux]

Rails Version:

Rails 4.2.5

CODE:

    ua = Net::HTTP.new(SERVER, 443)
    ua.instance_eval {
      @ssl_context = OpenSSL::SSL::SSLContext.new
      options = OpenSSL::SSL::OP_NO_SSLv2 | OpenSSL::SSL::OP_NO_SSLv3
      if OpenSSL::SSL.const_defined?('OP_NO_COMPRESSION')
        options |= OpenSSL::SSL::OP_NO_COMPRESSION
      end
      @ssl_context.set_params({options: options})
    }
   # ua.instance_eval { @ssl_context = OpenSSL::SSL::SSLContext.new(:TLSv1_2) }
    ua.use_ssl = true

    # Checks presence of CA certificate
    if File.directory?(RootCA)
      ua.ca_path = RootCA
      ua.verify_mode = OpenSSL::SSL::VERIFY_PEER
      ua.verify_depth = 3
    else
      puts "Invalid CA certificates directory. Exiting..."
      exit
    end

ERROR:

OpenSSL::SSL::SSLError: SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed
    from /home/cp/.rbenv/versions/2.3.0/lib/ruby/2.3.0/net/http.rb:933:in `connect_nonblock'
    from /home/cp/.rbenv/versions/2.3.0/lib/ruby/2.3.0/net/http.rb:933:in `connect'
    from /home/cp/.rbenv/versions/2.3.0/lib/ruby/2.3.0/net/http.rb:863:in `do_start'
    from /home/cp/.rbenv/versions/2.3.0/lib/ruby/2.3.0/net/http.rb:852:in `start'
    from /home/cp/.rbenv/versions/2.3.0/lib/ruby/2.3.0/net/http.rb:1398:in `request'
    from /home/cp/.rbenv/versions/2.3.0/lib/ruby/2.3.0/net/http.rb:1421:in `send_entity'
    from /home/cp/.rbenv/versions/2.3.0/lib/ruby/2.3.0/net/http.rb:1209:in `post'
Answers:

Issue resolved after building ruby with openssl (https://railsfornovice.wordpress.com/2017/03/02/fix-openssl-cert-error-in-rails/)

– loganathan | Score: 0

&lt;div&gt;&lt;ul&gt;&lt;li&gt;&lt;div&gt; SCRAPING RUBY with REGEX /w

Asked by Cindy Adriana Bohrquez Santana | Score: 0 | Answers: 1

I am looking to do scraping of the website https://www.bananatic.com/es/forum/games/

and extract the tags "name", "views" and "replies". I have a big problem to get the non-empty content of the "name" tag. Can you help me? I need to save only the elements that do have text.

This is my code, I have three variables:

Each array should contain only the elements that they have. something but in the names the writings [" "] are saved and I want them not to be saved in my array. enter image description here

    require 'nokogiri'
    require 'open-uri'
    require 'pp'
    require 'csv'


    unless File.readable?('data.html')
      url = 'https://www.bananatic.com/de/forum/games/'
      data = URI.open(url).read
      File.open('data.html', 'wb') { |f| f << data }
    end
    data = File.read('data.html')
    document = Nokogiri::HTML(data)


    per = document.xpath('//div[@class="replies"]/text()[string-length(normalize-space(.)) > 0]')
                  .map { |node| node.to_s[/\d+/] }

    p per

    pir = document.xpath('//div[@class="views"]/text()[string-length(normalize-space(.)) > 0]')
                  .map { |node| node.to_s[/\w+/] }

    p pir

    links2 = document.css('.topics ul li div')
    res = links2.map do |lk|
      name = lk.css('.name  p a').inner_text
      [name]
    end
    p res

To fix it I have added a regular expression, however I have failed in the attempt. I just replace .inner_textwith .to_s[/\w+/], but I don't get it. enter image description here

👇🏼 Now I have an array with null values ​​and some letters "a" that I don't know where they appear.

enter image description here

Answers:

This Might Help XPath and CSS.

For your CSS check this out: https://kittygiraudel.github.io/selectors-explained/

The following will get you what you are looking for

document.xpath('//div[@class="topics"]/ul/li//div[@class="name"]/a[@class="js-link avatar"]/text()').map {|node| node.to_s.strip}`.

If you want to understand where your array is coming from take 1 step back and just print out lk.css('.name p a').to_s but the real issue is your selectors are just off.

All that being said looking at the construct of the page you would be better off with something like this:

require 'nokogiri'
require 'open-uri'

url = "https://www.bananatic.com/de/forum/games/"

doc = Nokogiri::HTML(URI.open(url))
# Set a root node set to start from
topics = doc.xpath('//div[@class="topics"]/ul/li')

# loop the set 
details = topics.filter_map do |topic| 
  next unless topic.at_xpath('.//div[@class="name"]') # skip ones without the needed info
  # Map details into a Hash
  {name: topic.at_xpath('.//div[@class="name"]/a[@class="js-link avatar"]/text()').to_s.strip,
   post_year: topic.at_xpath('.//div[@class="name"]/text()[string-length(normalize-space(.)) > 0]').to_s[/\d{4}/],
   replies: topic.at_xpath('.//div[@class="replies"]/text()').to_s.strip, 
   views: topic.at_xpath('.//div[@class="views"]/text()').to_s.strip 
  }
end

The result of details would be:

[{:name=>"MrCasual2502", :post_year=>"2016", :replies=>"0", :views=>"236"},
 {:name=>"MrCasual2502", :post_year=>"2016", :replies=>"0", :views=>"164"},
 {:name=>"EdgarAllen", :post_year=>"2022", :replies=>"0", :views=>"1"},
 {:name=>"RAMONVC", :post_year=>"2022", :replies=>"0", :views=>"0"},
 {:name=>"RAMONVC", :post_year=>"2022", :replies=>"0", :views=>"1"},
 {:name=>"tokyobreez", :post_year=>"2021", :replies=>"2", :views=>"18"},
 {:name=>"matrix12334", :post_year=>"2022", :replies=>"0", :views=>"2"},
 {:name=>"juggalohomie420", :post_year=>"2017", :replies=>"3", :views=>"89"},
 {:name=>"Imas86", :post_year=>"2022", :replies=>"2", :views=>"2"},
 {:name=>"SmilesImposterr", :post_year=>"2021", :replies=>"1", :views=>"17"},
 {:name=>"bebb", :post_year=>"2019", :replies=>"7", :views=>"22"},
 {:name=>"IMBANANAZ", :post_year=>"2016", :replies=>"1", :views=>"4"},
 {:name=>"IWantSteamKeys", :post_year=>"2021", :replies=>"1", :views=>"4"},
 {:name=>"gamormoment", :post_year=>"2021", :replies=>"1", :views=>"47"},
 {:name=>"Lovestruck", :post_year=>"2021", :replies=>"3", :views=>"46"},
 {:name=>"KillerBotAldwin1", :post_year=>"2021", :replies=>"1", :views=>"95"},
 {:name=>"purplevestynstr", :post_year=>"2020", :replies=>"1", :views=>"13"},
 {:name=>"Janabanana", :post_year=>"2021", :replies=>"3", :views=>"3"},
 {:name=>"apache724", :post_year=>"2017", :replies=>"3", :views=>"33"},
 {:name=>"MrsSue66", :post_year=>"2021", :replies=>"1", :views=>"38"}]

– engineersmnky | Score: 1

Text preprocessing packages in addition to Mustache that are importable both into Python code and Ruby code

Asked by HippoMan | Score: -1 | Answers: 1

I'm running the latest versions of Python and Ruby under Debian Linux version 13.

I make use of text preprocessing both in Python and Ruby, and this is only used for preprocessing text in files that are external to Python and Ruby, and it's never used for preprocessing any code within my Python and Ruby programs themselves.

Because some of these external text files are read by one or more of my Python programs and also one or more of my Ruby programs, I need to use the same templating language for the preprocessing directives that are used in all of these external text files.

Furthermore, I never want to have to shell out to run a preprocessing executable, but rather, I only want to perform the preprocessing via an imported Python package and an imported Ruby package.

Therefore, I need to use a templating package that has versions which are importable into Python programs and also which are importable into Ruby programs.

The only preprocessor that I've found so far which offers a version that can be imported both into Python code and into Ruby code is Mustache (and some of its 3rd-party forks).

But Mustache is limited in that it doesn't offer constructs such as looping and conditional logic. Therefore, I'm looking for alternatives to Mustache which are importable as a Python package and also as a Ruby package.

I've investigated m4, cpp, gpp text preprocessor, Mozilla preprocessor, jinja2, filepp, cheetah, and several others, but so far, none that I've found offer all of the capabilities that I've described here.

Does anyone know of any Mustache alternatives which fit all of my criteria?

Answers:

It turns out that pycall.rb works for me and doesn't use up too much processing power, so I am now using it in ruby with Cheetah ... and also, of course, I'm using Cheetah directly in the python version of the code. Many thanks to Nick ODell!!!

And it also turns out that erblite is too "lite". Its functionality is a bit limited in comparison to the official ERB, and it also turns out that it handles local variables in python differently from how they are handled in ruby, and this complicates the use of erblite. Perhaps there is a way to work around this, but I decided to not bother spending any more time trying to do so, because of the fact that the pycall.rb/Cheetah set-up is working well for me.

And again, much appreciation to Nick ODell!!!

– HippoMan | Score: 2

How to test rate limit in Rails?

Asked by Chiara Ani | Score: 0 | Answers: 0

How can I test with RSpec I'm using rate_limit method on my Rails 8 app?

class SessionsController < ApplicationController
  rate_limit to: 10, within: 3.minutes, only: :create
end

How does Ruby manage localhost communications via TCP under Windows 7?

Asked by Jazzinghen | Score: 1 | Answers: 0

I am trying to implement a simple local TCP communication between a Ruby server and a C++ library interfaced to Unreal Engine 4.

I have used some sample code for the ruby server, which uses the socket library and instantiates a TCPServer:

require 'socket'

puts "Starting up server..."
# establish the server
## Server established to listen for connections on port 2008
server = TCPServer.new(15300)
# setup to listen and accept connections
while (session = server.accept)
 #start new thread conversation
 ## Here we will establish a new thread for a connection client
 Thread.start do
   ## I want to be sure to output something on the server side
   ## to show that there has been a connection
   puts "log: Connection from #{session.peeraddr[2]} at
          #{session.peeraddr[3]}"
   puts "log: got input from client"
   ## lets see what the client has to say by grabbing the input
   ## then display it. Please note that the session.gets will look
   ## for an end of line character "\n" before moving forward.
   input = session.gets
   puts input
   ## Lets respond with a nice warm welcome message
   session.puts "Server: Welcome #{session.peeraddr[2]}\n"
   # reply with goodbye
   ## now lets end the session since all we wanted to do is
   ## acknowledge the client
   puts "log: sending goodbye"
   session.puts "Server: Goodbye\n"
 end  #end thread conversation
end   #end loop

This application, if tested with a ruby client, works perfectly fine.

This is the client:

require 'socket'
# establish connection
## We need to tell the client where to connect
## Conveniently it is on localhost at port 15300!
clientSession = TCPSocket.new( "localhost", 15300 )
puts "log: starting connection"
#send a quick message
## Note that this has a carriage return. Remember our server
## uses the method gets() to get input back from the server.
puts "log: saying hello"
clientSession.puts "Client: Hello Server World!\n"
#wait for messages from the server
## You've sent your message, now we need to make sure
## the session isn't closed, spit out any messages the server
## has to say, and check to see if any of those messages
## contain 'Goodbye'. If they do we can close the connection
 while !(clientSession.closed?) &&
          (serverMessage = clientSession.gets)
  ## lets output our server messages
  puts serverMessage
  #if one of the messages contains 'Goodbye' we'll disconnect
  ## we disconnect by 'closing' the session.
  if serverMessage.include?("Goodbye")
   puts "log: closing connection"
   clientSession.close
  end
 end #end loop

Server output:

Starting up server...
log: Connection from ::1 at
          ::1
log: got input from client
Client: Hello Server World!
log: sending goodbye

But when I try to connect to the server using C++11 and the TCP functions in Unreal Engine 4 I do not get any kind of response from the server implemented in ruby (not even "Connection from...").

To understand what was the problem I tried to run some network analysis, starting from the simplest (Window's Resource Monitor), to the most complex (ZenMap). In no case there was a single service running with the selected port open (port 15300). I have double checked every single possible cause for this (e.g. firewall, other security software) but there was no block to the ruby interpreter.

In order to understand why such a simple application is not working I started using Wireshark. It was then that I noticed that there is no local loopback interface, which required me to use RawCap (which manages to capture the local communications and dump them on file). Using it I managed to dump the local communications on my machine during both a run of the ruby client/server pair and Cygwin Socat/Unreal Engine 4. What I found was pretty baffling: there were NO open local TCP sockets on the port for the ruby pair (port 15300), but the TCP ports opened by Unreal Engine 4 were there (along with port 15301, the one I used for the tests).

Update 01

I have changed the code in my Unreal Engine 4 application, as the first version used an included TCPsocket builder which used bind by default instead of connect. Now the code is:

bool UNetworkBlueprintLibrary::NetworkSetup(int32 ServerPort) {

    bool res = false;

    // Creating a Socket pointer, which will temporary contain our 
    FSocket* Socket = nullptr;
    ISocketSubsystem* SocketSubsystem = ISocketSubsystem::Get(PLATFORM_SOCKETSUBSYSTEM);
    
    // Instead of that useless FTcpSocketBuilder I will try to create the socket by hand and then debug it... >:(
    if (SocketSubsystem != nullptr) {
        // Try to create a stream socket using the system-intependent interface
        Socket = SocketSubsystem->CreateSocket(NAME_Stream, TEXT("Server Socket"), false);

        if (Socket != nullptr) {
            FIPv4Address ServerAddress = FIPv4Address(127, 0, 0, 1);
            TSharedRef<FInternetAddr> LocalAddress = ISocketSubsystem::Get(PLATFORM_SOCKETSUBSYSTEM)->CreateInternetAddr();
            uint16 castServerPort = (uint16)ServerPort;

            // Attach received port and IPAddress to Internet Address pointer
            LocalAddress->SetIp(ServerAddress.GetValue());
            LocalAddress->SetPort(castServerPort);
            
            bool SocketCreationError = !Socket->Connect(*LocalAddress);

            if (SocketCreationError)
            {
                GLog->Logf(TEXT("Failed to create Server Socket as configured!"));

                SocketSubsystem->DestroySocket(Socket);
                    
                Socket = nullptr;
            }
        }
    }



    if (Socket != nullptr){
        UNetworkBlueprintLibrary::ServerSocket = Socket;
        res = true;
    }
    else {
        res = false;
    }

    return res;
} 

In order to test whether the code in Unreal Engine 4 is working or not I have used socat under Cygwin:

socat tcp-listen:15300 readline

Once my Unreal Engine 4 application starts I can send data over the socket. I have confirmed this works, removing the possibility that my application developed in Unreal Engine 4 was not communicating through the TCP socket.

Given this positive result I have tried again to use the server code reported on top of this question, removing the lines that wait for a message from the client but the result is the same: the server does not even output the debug lines it should print when there is a connection:

puts "log: Connection from #{session.peeraddr[2]} at #{session.peeraddr[3]}"

Update 02

Back once again!

I have managed to make ruby and Unreal Engine 4 communicate through local TCP sockets. What I needed to make the ruby server work was explicitly providing the local address, like so:

server = TCPServer.new("127.0.0.1", 15300)

However, even if this matter is solved, I am still interested in some of the questions I put the first time.

Update 03

Just one consideration that I made in the last hour.

When I did not provide an explicit server address the server, this command

   puts "log: Connection from #{session.peeraddr[2]} at
          #{session.peeraddr[3]}"

Returned

log: Connection from ::1 at
          ::1

Which is indeed correct! ::1 is the IPv6 version of 127.0.0.1, so it looks like that ruby assumes that it has to create an IPv6 socket, instead of an IPv4. Unreal Engine 4 does not provide an IPv6 interface, so this might have been the reason why the application did not work.

Now communications over localhost when dumped, show the following communications over port 15300:

No.     Time        Source                Destination           Protocol Length Info
    105 7.573433    127.0.0.1             127.0.0.1             TCP      52     9994→15300 [SYN] Seq=0 Win=8192 Len=0 MSS=65495 WS=256 SACK_PERM=1
    106 7.573433    127.0.0.1             127.0.0.1             TCP      52     15300→9994 [SYN, ACK] Seq=0 Ack=1 Win=8192 Len=0 MSS=65495 WS=256 SACK_PERM=1
    107 7.573433    127.0.0.1             127.0.0.1             TCP      40     9994→15300 [ACK] Seq=1 Ack=1 Win=8192 Len=0
    108 7.583434    127.0.0.1             127.0.0.1             TCP      66     15300→9994 [PSH, ACK] Seq=1 Ack=1 Win=8192 Len=26
    109 7.583434    127.0.0.1             127.0.0.1             TCP      40     9994→15300 [ACK] Seq=1 Ack=27 Win=7936 Len=0
    110 7.583434    127.0.0.1             127.0.0.1             TCP      56     15300→9994 [PSH, ACK] Seq=27 Ack=1 Win=8192 Len=16
    111 7.583434    127.0.0.1             127.0.0.1             TCP      40     9994→15300 [ACK] Seq=1 Ack=43 Win=7936 Len=0
    208 16.450941   127.0.0.1             127.0.0.1             TCP      52     9995→15300 [SYN] Seq=0 Win=8192 Len=0 MSS=65495 WS=256 SACK_PERM=1
    209 16.451941   127.0.0.1             127.0.0.1             TCP      52     15300→9995 [SYN, ACK] Seq=0 Ack=1 Win=8192 Len=0 MSS=65495 WS=256 SACK_PERM=1
    210 16.451941   127.0.0.1             127.0.0.1             TCP      40     9995→15300 [ACK] Seq=1 Ack=1 Win=8192 Len=0
    211 16.456941   127.0.0.1             127.0.0.1             TCP      66     15300→9995 [PSH, ACK] Seq=1 Ack=1 Win=8192 Len=26
    212 16.456941   127.0.0.1             127.0.0.1             TCP      40     9995→15300 [ACK] Seq=1 Ack=27 Win=7936 Len=0
    213 16.456941   127.0.0.1             127.0.0.1             TCP      56     15300→9995 [PSH, ACK] Seq=27 Ack=1 Win=8192 Len=16
    214 16.456941   127.0.0.1             127.0.0.1             TCP      40     9995→15300 [ACK] Seq=1 Ack=43 Win=7936 Len=0

When a packages show a LEN of either 26 or 16 means that they are sending either

Server: Welcome 127.0.0.1.

or

Server: Goodbye.

I just wanted to share this information, as it is not really useful for the answer, but shows how IPv6 communications do not pass through the standard localhost virtual adapter.

The questions

What I would like to understand is:

Ruby 3.3, method that takes **options as an argument errors when passed an empty hash

Asked by Max Williams | Score: -3 | Answers: 1

I am calling a method that takes an argument and also uses `**options` to convert remaining key-pair values into a hash. Here's a simpler example method that does the same thing.

def foo(arg1, **options)
  [arg1, options]
end

Here's some example calls:

> foo("hello")

=> ["hello", {}]

> foo("hello", :opt1 => "one")

=> ["hello", {:opt1=>"one"}]

> foo("hello", :opt1 => "one", :opt2 => "two")

=> ["hello", {:opt1=>"one", :opt2=>"two"}]

So, we can see it converting the key-values into a hash which is saved as 'options' variable. So far so good.

The problem comes when I try to pass through an actual hash, like so:

> foo("hello", {})
ArgumentError: wrong number of arguments (given 2, expected 1)

I expected this to work like in older versions of ruby, where the standard pattern would be

def foo(arg1, options={})
  [arg1, options]
end

Which can be called like

foo("hello", :opt1 => "one", :opt2 => "two")

but can also be called like this:

foo("hello", {})

This is a standard pattern, of passing a hash of options around between methods. In this case, the method i'm calling is one of the built-in rails methods. How can i pass it a hash to use as **options? The hash might be empty.

Answers:

I found the answer with some experiment: I need to put ** before the hash i'm passing through, eg

> hash = {}
=> {}
> foo("hello", **hash)
=> ["hello", {}]

– Max Williams | Score: 2

DataMapper to migrate data from one table to another.

Asked by Namrata K | Score: -1 | Answers: 1

If I am using DataMapper, and I have two databases, is there any way using migration.rb to copy a table for example table person from database 1 to database 2? (same schema and table values).

Referring this:https://github.com/datamapper/dm-migrations/blob/master/examples/sample_migration.rb

It only tells me how to add/modify/drop tables.

Thanks for help.

Answers:

I don't think that's the intention of dm-migrations. I believe the easiest way would be something like this:

DataMapper.setup(:default, db1_config)
DataMapper.setup(:new, db2_config)
class Foo
  include DataMapper::Resource
  property :id, Serial
  property :name, String
  ...
end
DataMapper.finalize

Foo.each do |foo|
  DataMapper.repository(:new) do
    # It may not let you set the "id" attribute here...
    Foo.create(foo.attributes)
  end
end

Edit

In hindsight, I'm not sure if you were asking how to to copy table structure as to opposed to table data. This is obviously copying table data.

– bioneuralnet | Score: 0