How does Domino deal with a dashed class name - ruby

I'm attempting to create and use domino to abstract a login page
describe :index, :type => :request do
before do
visit '/'
blah_email_login('user1')
end
...
def blah_email_login(user)
Dom::Email_Link.find_by_name 'Mail'.click
....
end
module Dom
class Email_Link < Domino
selector 'a'
attribute :tab-label
end
here is the html
<a class="tab-label fz-xs accent " href="https://mail.blah.com/..." id="blah"><span class="tab-icon img-sprite"></span><em class="strong tab-link-txt y-link-1 " title="Mail">Mail</em></a>
The process cannot take a dash as indicated my the error I get pre run
C:\blah.rb:93:in `<class:Email_Link>': undefined local variable or method `label' for Dom::Email_Link:Class (NameError)
When I attempted to alter attribute to
attribute :'tab-label'
I got ...
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/domino-0.5.0/lib/domino.rb:114:in `class_eval': (eval):2: syntax error, unexpected '-', expecting ';' or '\n' (SyntaxError)
def tab-label
^
When I included escape characters
attribute :'tab\-label'
I got ...
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/domino-0.5.0/lib/domino.rb:114:in `class_eval': (eval):2: syntax error, unexpected $undefined, expecting ';' or '\n' (SyntaxError)
def tab\-label
^
(eval):4: syntax error, unexpected $undefined, expecting ']'
if value && self.class.callbacks[:tab\-label].is_a?(Proc)
The site I'm working with has many dashed class names, any ideas on how to work with that?

Try:
module Dom
class Email_Link < Domino
selector 'a'
attribute :'tab-label'
end
Update
Domino's default behavior is to replace _ in attribute names to - in class names (see here).
Therefore your attribute name should use underscore:
module Dom
class Email_Link < Domino
selector 'a'
attribute :tab_label
end

Related

Ruby: unexpected ',', expecting keyword_end

Very new to Ruby, unable to see the titular syntax error in this bit of code:
#! /usr/bin/env ruby
require 'sensu-plugin/metric/cli'
class MetricAvailableUpdates < Sensu::Plugin::Metric::CLI::Graphite
option :scheme,
description: 'Metric naming scheme',
long: '--scheme SCHEME',
short: '-s SCHEME',
default: "#{Socket.gethostname}"
def run
# Get the metrics.
output = %x[/usr/lib/update-notifier/apt-check --human-readable]
output_lines = output.split(/(\n)/)
metrics = {}
updates_pattern = " packages can be updated."
updates = output_lines[0].tr(upgrades_pattern, "").to_i
metrics[:available_updates] = updates
security_updates_pattern = " updates are security updates."
security_updates = output_lines[2].tr(security_updates_pattern, "").to_i
metrics[:available_security_updates] = security_updates
# Print them in graphite format.
metrics.each do |k, v|
output [config[:scheme], k].join('.'), v
end
# Done
ok
end
end
I can add the code that precedes this if the syntax error is in fact before this section. Edit: added complete file contents per comment request
The complete error, in case that is useful:
./metrics-available-updates.rb:29: syntax error, unexpected ',', expecting keyword_end
output [config[:scheme], k].join('.'), v
If you play around a bit, you will notice that the syntax error goes away either when you comment out the offending line, or alternatively the line
output = %x[/usr/lib/update-notifier/apt-check --human-readable]
When Ruby parses a file, it needs to guess, whether a symbol denotes a method call, or a variable reference. In this case, output springs into existence as a variable, but further down, you write
output [config[:scheme], k].join('.'), v
which means it suddenly becomes a method call.
I admit that the Ruby lexer should give a more helpful error message....
Add the parentheses
...
metrics.each do |k, v|
output([config[:scheme], k].join('.'), v)
end
...

syntax error, unexpected ')', expecting '='

I'm writing an extension for Redcarpet for a Jekyll-powered website. I want to use {x|y} as a tag in markdown that evaluates to the HTML <ruby> tag (and its associates). I wrote this class as per Jekyll's guide, Redcarpet's guide, and this guide on how to do so:
class Jekyll::Converters::Markdown::HotelDown < Redcarpet::Render::HTML
def preprocess(doc)
s = "<ruby><rb>\\1</rb><rp>(</rp><rt>\\2</rt><rp>)</rp></ruby>"
doc.gs­ub!(/\[([\­s\S]+)\|([­\s\S]+)\]/­, s)
doc
end
end
But, I seem to be getting a couple errors when I run bundle exec jekyll serve:
Configuration file: C:/Users/Alex/OneDrive/codes/hotelc.me/hotelc.me/_config.yml
plugin_manager.rb:58:in `require': HotelDown.rb:4: syntax error, unexpected tIDENTIFIER, expecting ')' (SyntaxError)
doc.gs-ub!(/\[([\-s\S]+)\|([-\s\S]+)\]/-, s)
^
HotelDown.rb:4: syntax error, unexpected ')', expecting '='
doc.gs-ub!(/\[([\-s\S]+)\|([-\s\S]+)\]/-, s)
^
It seems there's something wrong with my syntax (an extra space, missing parentheses, or something like that). Is there something I've missed?
Your code has some special characters which is causing this error:
syntax error, unexpected ')', expecting '='
doc.gs-ub!(/\[([\-s\S]+)\|([-\s\S]+)\]/-, s)
Replace your current code with this piece of code:
class Jekyll::Converters::Markdown::HotelDown < Redcarpet::Render::HTML
#Overriding the preprocess() function
def preprocess(doc)
s = "<ruby><rb>\\1</rb><rp>(</rp><rt>\\2</rt><rp>)</rp></ruby>"
doc.gsub!(/\[([\s\S]+)\|([\s\S]+)\]/, s)
doc
end
end
markdown = Redcarpet::Markdown.new(HotelDown)
and it should work!

Syntax error in for loop (Ruby/RSpec)

While running the RSPEC test as shown below im getting this error:
Using Accessor#strict_set for specs
SyntaxError: /home/sam/projects/logstash.king-foo.dev/ansible/roles/logstash/spec/syslog.rb:6: syntax error, unexpected kEND
end
^
load at org/jruby/RubyKernel.java:1101
(root) at /opt/logstash/vendor/bundle/jruby/1.9/gems/rspec-core-2.14.7/lib/rspec/core/configuration.rb:1
each at org/jruby/RubyArray.java:1613
load_spec_files at /opt/logstash/vendor/bundle/jruby/1.9/gems/rspec-core-2.14.7/lib/rspec/core/configuration.rb:896
load_spec_files at /opt/logstash/vendor/bundle/jruby/1.9/gems/rspec-core-2.14.7/lib/rspec/core/configuration.rb:896
run at /opt/logstash/vendor/bundle/jruby/1.9/gems/rspec-core-2.14.7/lib/rspec/core/command_line.rb:22
I tried messing around with the syntax but without success.
files = Dir['../configs/filter*.conf']
##configuration = String.new
files.sort.each.do |file|
##configuration << File.read(file)
end
describe "my first logstash rspec test", :if => RUBY_ENGINE == "jruby" do
extend LogStash::RSpec
config(##configuration)
... some code here ...
end
Does anybody know what i'm doing wrong?
Why do i get a syntax error for the end statement ander the ##configuration variable?
The error means there was an unexpected end in your code. Just simply replace the 3rd line with
files.sort.each do |file|
I optionally recommend you use { and } instead of do and end. The { and } are space-insensitive and you are less likely to receive an error than do and end.

Ruby - Microsoft Translator unexpected token error

I'm using the following method to translate a simple word from English to Russian by calling:
translate("hello")
This is my method:
def translate(text)
begin
uri = "http://api.microsofttranslator.com/V2/Ajax.svc/GetTranslations?appId=#{#appid}&text=#{text.strip}&from=en&to=ru&maxTranslations=1"
page = HTTParty.get(uri).body
show_info = JSON.parse(page) # this line throws the error
rescue
puts $!
end
end
The JSON output:
{"From":"en","Translations":[{"Count":0,"MatchDegree":100,"MatchedOriginalText":"","Rating":5,"TranslatedText":"Привет"}]}
The error:
unexpected token at '{"From":"en","Translations":[{"Count":0,"MatchDegree":100,"MatchedOriginalText":"","Rating":5,"TranslatedText":"Привет"}]}'
Not sure what it means by unexpected token. It's the only error I'm receiving. Unfortunately I can't modify the JSON output as it's returned by the API itself.
UPDATE:
Looks like the API is returning some illegal characters (bad Microsoft):
'´╗┐{"From":"en","Translations":[{"Count":0,"MatchDegree":0,"Matched OriginalText":"","Rating":5,"TranslatedText":"Hello"}]}'
Full error:
C:/Ruby193/lib/ruby/1.9.1/json/common.rb:148:in `parse': 743: unexpected token at '´╗┐{"From":"en","Translations":[{"Count":0,"MatchDegree":0,"Matched
OriginalText":"","Rating":5,"TranslatedText":"Hello"}]}' (JSON::ParserError)
from C:/Ruby193/lib/ruby/1.9.1/json/common.rb:148:in `parse'
from trans.rb:13:in `translate'
from trans.rb:17:in `<main>'
Try ensuring UTF-8 encoding and stripping any leading BOM indicators in the string:
# encoding: UTF-8
# ^-- Make sure this is on the first line!
def translate(text)
begin
uri = "http://api.microsofttranslator.com/V2/Ajax.svc/GetTranslations?appId=#{#appid}&text=#{text.strip}&from=en&to=ru&maxTranslations=1"
page = HTTParty.get(uri).body
page.force_encoding("UTF-8").gsub!("\xEF\xBB\xBF", '')
show_info = JSON.parse(page) # this line throws the error
rescue
puts $!
end
end
Sources:
Ruby 1.9's String
Wikipedia: Byte order mark
Using awk to remove the Byte-order mark

quotes issue (ruby)

any idea how I can pass correct argument to xpath? There must be something about how to use single/double quotes. When I use variable
parser_xpath_identificator = "'//table/tbody[#id=\"threadbits_forum_251\"]/tr'" gives me an incorrect value or
parser_xpath_identificator = "'//table/tbody[#id="threadbits_forum_251"]/tr'" gives me an error syntax error, unexpected tIDENTIFIER, expecting $end
require 'rubygems'
require 'mechanize'
parser_xpath_identificator = "'//table/tbody[#id=\"threadbits_forum_251\"]/tr'"
# parser_xpath_identificator = "'//table/tbody[#id="threadbits_forum_251"]/tr'"
#gives an error: syntax error, unexpected tIDENTIFIER, expecting $end
agent = WWW::Mechanize.new
page = agent.get("http://www.vbulletin.org/forum/index.php")
page = page.link_with(:text=>'vB4 General Discussions').click
puts "Page title: #{page.title}"
puts "\nfrom variable: #{page.parser.xpath(parser_xpath_identificator).length}"
puts "directly: #{page.parser.xpath('//table/tbody[#id="threadbits_forum_251"]/tr').length}"
In both cases you're nesting single-quotes directly inside double-quotes, which I don't think is correct. Try this:
parser_xpath_identificator = '//table/tbody[#id="threadbits_forum_251"]/tr'

Resources