repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
sonots/triglav
app/serializers/job_message_each_serializer.rb
class JobMessageEachSerializer < ActiveModel::Serializer attributes :id, :job_id, :time, :timezone include Swagger::Blocks swagger_schema :JobMessageEachResponse do property :id do key :type, :integer key :format, :int64 end property :job_id do key :type, :integer key :format, :int64 key :description, 'Job ID' end property :time do key :type, :integer key :description, 'Time of event in unix timestamp such as 1476025200 (2016-10-10 in +09:00)' end property :timezone do key :type, :string key :description, 'Timezone of event time, that is, timezone of %Y-%m-%d for hdfs://path/to/%Y-%m-%d such as +09:00' end end end
sonots/triglav
app/models/settings.rb
# NOTE: This file would be `require`ed by unicorn.rb before loading rails require 'settingslogic' class Settings < Settingslogic source File.expand_path("../../config/settings.yml", __dir__) namespace defined?(Rails) ? Rails.env : ENV['RACK_ENV'] # unicorn -E RACK_ENV end
sonots/triglav
lib/triglav/error/not_authorized.rb
<reponame>sonots/triglav module Triglav module Error class NotAuthorized < Triglav::Error::StandardError def initialize @code = 403 @message = "Not authorized." end end end end
sonots/triglav
app/controllers/api/v1/auth_controller.rb
<filename>app/controllers/api/v1/auth_controller.rb<gh_stars>1-10 module Api module V1 class AuthController < ApplicationController include Swagger::Blocks before_action :authenticate!, only: [:destroy, :me] swagger_path '/auth/token' do operation :post do key :description, 'Creates a new token' key :operationId, 'createToken' key :tags, ['auth'] parameter do key :name, :credential key :in, :body key :required, true schema do key :'$ref', :Credential end end response 200 do key :description, 'access token response' schema do key :'$ref', :TokenResponse end end response :default do key :description, 'unexpected error' schema do key :'$ref', :ErrorModel end end end end def create user = User.authenticate(sign_in_params) api_key = ApiKey.create(user_id: user.id) if user if user and api_key self.current_user = user render json: api_key else raise Triglav::Error::InvalidAuthenticityCredential end end swagger_path '/auth/token' do operation :delete do key :description, 'Deletes (Expires) a token of header' key :operationId, 'deleteToken' key :tags, ['auth'] security do key :api_key, [] end response 204 do key :description, 'deleted' end response :default do key :description, 'unexpected error' schema do key :'$ref', :ErrorModel end end end end def destroy self.current_user = nil ApiKey.find_by(access_token: current_access_token).try(:destroy) head :no_content end swagger_path '/auth/me' do operation :get do key :description, 'Returns a user property of the access_token' key :operationId, 'me' key :tags, ['auth'] security do key :api_key, [] end response 200 do key :description, 'user response' schema do key :'$ref', :UserResponse end end response :default do key :description, 'unexpected error' schema do key :'$ref', :ErrorModel end end end end def me render json: current_user end private def sign_in_params params.require(:username) params.require(:password) params.permit(:username, :password, :authenticator) end end end end
sonots/triglav
app/serializers/aggregated_resource_each_serializer.rb
class AggregatedResourceEachSerializer < ActiveModel::Serializer attributes :uri, :unit, :timezone, :span_in_days include Swagger::Blocks swagger_schema :AggregatedResourceEachResponse do property :uri do key :type, :string key :description, "resource uri" end property :unit do key :type, :string key :description, "'singular' or 'daily' or 'hourly', or their combinations such as 'daily,hourly', 'daily,hourly,singular'" end property :timezone do key :type, :string key :description, "timezone of the format [+-]HH:MM" end property :span_in_days do key :type, :integer key :format, :int64 key :description, "span in days" end end end
sonots/triglav
spec/requests/api/v1/auth_spec.rb
<gh_stars>1-10 # coding: utf-8 require 'rails_helper' RSpec.describe 'Auth', :type => :request do describe "Get token", :autodoc do let(:description) do "Returns access_token if authenticated.<br/>" \ "Authenticate with username, password registered via /api/v1/users<br/>" \ "If other APIs are requested with valid token, the expiration time of the token is extended<br/>" end let(:env) do { 'CONTENT_TYPE' => 'application/json', 'HOST' => 'triglav.analytics.mbga.jp', 'HTTP_ACCEPT' => 'application/json', } end let(:params) do { username: 'test_user', password: '<PASSWORD>', } end before do FactoryGirl.create( :user, :read_only, name: 'test_user', password: '<PASSWORD>' ) end it "POST /api/v1/auth/token" do post "/api/v1/auth/token", params: params.to_json, env: env expect(response.status).to eq 200 end end describe "Revoke token", :autodoc do let(:description) do "Revoke access_token specified in Authorization header" end let(:params) do {} end let(:env) do { 'CONTENT_TYPE' => 'application/json', 'HOST' => 'medjed.analytics.mbga.jp', 'HTTP_ACCEPT' => 'application/json', 'HTTP_AUTHORIZATION' => access_token, } end let(:access_token) do ApiKey.create(user_id: user.id).access_token end let(:user) do FactoryGirl.create(:user, :read_only) end it "DELETE /api/v1/auth/token" do delete "/api/v1/auth/token", params: params, env: env expect(response.status).to eq 204 end end describe "Current user", :autodoc do let(:description) do "Returns user associted with the token specified in Authorization header<br/>" \ "The expiration time is extended if the token is valid<br/>" end let(:params) do {} end let(:env) do { 'CONTENT_TYPE' => 'application/json', 'HOST' => 'medjed.analytics.mbga.jp', 'HTTP_ACCEPT' => 'application/json', 'HTTP_AUTHORIZATION' => access_token, } end let(:access_token) do ApiKey.create(user_id: user.id).access_token end let(:user) do FactoryGirl.create(:user, :editor, name: 'editorial_user') end it "GET /api/v1/auth/me" do get "/api/v1/auth/me", params: params, env: env expect(response.status).to eq 200 end end end
sonots/triglav
app/serializers/message_each_serializer.rb
<filename>app/serializers/message_each_serializer.rb class MessageEachSerializer < ActiveModel::Serializer attributes :id, :resource_uri, :resource_unit, :resource_time, :resource_timezone, :payload, :created_at, :updated_at include Swagger::Blocks swagger_schema :MessageEachResponse do allOf do schema do key :'$ref', :MessageResponse end end end swagger_schema :MessageFetchRequest, required: [:offset] do property :offset do key :type, :integer key :format, :int64 key :description, 'Offset (Greater than or equal to) ID for Messages to fetch from' end property :limit do key :type, :integer key :format, :int64 key :description, 'Number of limits' end property :resource_uris do key :type, :array key :description, 'URIs of Resource' items do key :type, :string end end end end
sonots/triglav
script/purge.rb
<reponame>sonots/triglav<filename>script/purge.rb #!/usr/bin/env ruby # Purge messages table # # $ script/purge.rb --purge-date 32 --exec require_relative '../lib/rails_runner' require 'optparse' class Purge class CLI DEFAULT_PURGE_DATE = 32 attr_reader :opts, :args def initialize @opts, @args = parse_options end def parse_options(argv = ARGV) op = OptionParser.new self.class.module_eval do define_method(:usage) do |msg = nil| puts op.to_s puts "error: #{msg}" if msg exit 1 end end opts = { exec: false, purge_date: DEFAULT_PURGE_DATE.days.ago.strftime('%Y-%m-%d'), } op.on('--exec', "Run (default: dry-run)") {|v| opts[:exec] = v } op.on('--purge-date VALUE', "Purge data before specified days (default: #{DEFAULT_PURGE_DATE} days ago)") {|v| opts[:purge_date] = Integer(v).days.ago.strftime('%Y-%m-%d') } op.banner += '' begin args = op.parse(argv) rescue OptionParser::InvalidOption => e usage e.message end [opts, args] end def dry_run? !@opts[:exec] end # %Y-%m-%d def purge_date @opts[:purge_date] end def run $stdout.puts "Purge before: #{purge_date}" purge(Message) purge(JobInternalMessage) purge(JobMessage) $stderr.puts "DRY-RUN finished. Use --exec" if dry_run? end def purge(klass) objs = klass.select(:id, :updated_at).where("updated_at < ?", purge_date) objs.each do |obj| $stdout.puts "Delete #{klass.to_s} id: #{obj.id}, updated_at: #{obj.updated_at.iso8601}" end objs.destroy_all unless dry_run? end end end Purge::CLI.new.run
sonots/triglav
spec/requests/api/v1/jobs_spec.rb
<reponame>sonots/triglav # coding: utf-8 require 'rails_helper' RSpec.describe 'Job resources', :type => :request do let(:params) do {} end let(:env) do { 'CONTENT_TYPE' => 'application/json', 'HOST' => 'triglav.analytics.mbga.jp', 'HTTP_ACCEPT' => 'application/json', 'HTTP_AUTHORIZATION' => access_token, } end let(:access_token) do ApiKey.create(user_id: user.id).access_token end let(:user) do FactoryGirl.create(:user, :triglav_admin) end let(:job) do FactoryGirl.create(:job_with_resources) end describe "Create or update a job" do let(:description) do "Create or update a job along with creating or updating resources.<br/>" \ "<br/>" \ "Create a job if its id is not given, and update a job if its id is given.<br/>" \ "Create resources if ids are not given for input and output resources, and update resources if ids are given for input and output resources. Destroy resources if ids of existing resources are not givens.<br/>" \ "<br/>" \ "`logical_op` is optional (default is `or`). With `and`, a job_message event is fired if all input resources' events are set. With `or`, a job_message event is fired if one of input resources' event is set.<br/>" \ "`span_in_days` is optional, and automatically filled with default value for both input and output resources.<br/>" \ "`consumable` for input resources are automatically set to true because this job will consume events for the input resource.<br/>" \ "`notifiable` for output resources should be set to 'true' only if the registered job will notify the end of job to triglav (i.e, send messages directly without triglav agent).<br/>" end describe "Create a job" do let(:job) do FactoryGirl.build(:job) end let(:input_resources) do [ FactoryGirl.build(:resource, uri: "resource://input/uri/0"), FactoryGirl.build(:resource, uri: "resource://input/uri/1"), ] end let(:output_resources) do [ FactoryGirl.build(:resource, uri: "resource://output/uri/0"), FactoryGirl.build(:resource, uri: "resource://output/uri/1", notifiable: true), ] end let(:input_resource_params) do %w[description uri unit timezone] end let(:output_resource_params) do %w[description uri unit timezone notifiable] end let(:params) do job.attributes.except('created_at', 'updated_at').merge({ input_resources: input_resources.map {|r| r.attributes.slice(*input_resource_params) }, output_resources: output_resources.map {|r| r.attributes.slice(*output_resource_params) }, }) end it "PUT/PATCH /api/v1/jobs", :autodoc do put "/api/v1/jobs", params: params.to_json, env: env expect(response.status).to eq 200 expect(Job.all.size).to eq(1) expect(JobsInputResource.all.size).to eq(2) expect(JobsOutputResource.all.size).to eq(2) expect(Resource.all.size).to eq(4) end end describe "Update a job" do let(:job) do FactoryGirl.create(:job) end let(:input_resources) do [ FactoryGirl.create(:resource, uri: "resource://input/uri/0"), FactoryGirl.create(:resource, uri: "resource://input/uri/1"), ] end let(:output_resources) do [ FactoryGirl.create(:resource, uri: "resource://output/uri/0"), FactoryGirl.create(:resource, uri: "resource://output/uri/1"), ] end let(:params) do job.attributes.merge({ input_resources: input_resources.map {|r| r.attributes.slice(*ResourceSerializer.request_permit_params.map(&:to_s)) }, output_resources: output_resources.map {|r| r.attributes.slice(*ResourceSerializer.request_permit_params.map(&:to_s)) }, }) end it "PUT/PATCH /api/v1/jobs" do put "/api/v1/jobs", params: params.to_json, env: env expect(response.status).to eq 200 expect(Job.all.size).to eq(1) expect(JobsInputResource.all.size).to eq(2) expect(JobsOutputResource.all.size).to eq(2) expect(Resource.all.size).to eq(4) end end end describe "Get a job" do let(:description) do "Get a job<br/>" end it "GET /api/v1/jobs/:id_or_uri" do get "/api/v1/jobs/#{job.id}", params: params, env: env expect(response.status).to eq 200 end it "GET /api/v1/jobs/:id_or_uri", :autodoc do get "/api/v1/jobs/#{CGI.escape(job.uri)}", params: params, env: env expect(response.status).to eq 200 end end describe "Delete a job", :autodoc do let(:description) do "Delete a job" end let(:job) do FactoryGirl.create(:job) end it "DELETE /api/v1/jobs/:job_id" do delete "/api/v1/jobs/#{job.id}", params: params, env: env expect(response.status).to eq 204 end end end
sonots/triglav
app/serializers/job_serializer.rb
class JobSerializer < ActiveModel::Serializer attributes :id, :uri, :logical_op, :created_at, :updated_at has_many :input_resources has_many :output_resources def self.request_params(params) params.permit( :id, :uri, input_resources: ResourceSerializer.request_permit_params, output_resources: ResourceSerializer.request_permit_params, ) end include Swagger::Blocks swagger_schema :JobResponse do allOf do schema do key :'$ref', :JobRequest end schema do property :created_at do key :type, :string key :format, :"date-time" end property :updated_at do key :type, :string key :format, :"date-time" end property :input_resources do key :type, :array key :description, 'Input resources' items do key :'$ref', :ResourceResponse end end property :output_resources do key :type, :array key :description, 'Output resources' items do key :'$ref', :ResourceResponse end end end end end swagger_schema :JobRequest do property :id do key :type, :integer key :format, :int64 end property :uri do key :type, :string end property :logical_op do key :type, :string end property :input_resources do key :type, :array key :description, 'New resources are created if id is not given. Update if id is given' items do key :'$ref', :ResourceRequest end end property :output_resources do key :type, :array key :description, 'New resources are created if id is not given. Update if id is given' items do key :'$ref', :ResourceRequest end end end end
sonots/triglav
lib/tasks/ridgepole.rake
require "open3" namespace :db do def apply(argopts) config_file = File.join("#{Rails.root}", "config", "database.yml") schema_file = File.join("#{Rails.root}", "db", "schemas", "Schemafile") command = "ridgepole --file #{schema_file} -c #{config_file} --ignore-table repli_chk,repli_clock #{argopts} -E #{Rails.env}" puts command out = [] Open3.popen2e(command) do |stdin, stdout_and_stderr, wait_thr| stdin.close stdout_and_stderr.each_line do |line| out << line yield(line) if block_given? end end out.join("\n") end desc "apply schema with ridgepole" task :apply do |t, args| apply('--apply') do |line| puts line end end desc "apply-dry-run schema with ridgepole" task :'apply-dry-run' do |t, args| apply('--apply --dry-run') do |line| puts line end end end namespace :ridgepole do end
sonots/triglav
app/serializers/message_serializer.rb
class MessageSerializer < ActiveModel::Serializer attributes :id, :uuid, :resource_uri, :resource_unit, :resource_time, :resource_timezone, :payload, :created_at, :updated_at def self.request_params(params) params.permit(*request_permit_params) end def self.request_permit_params [ :uuid, :resource_uri, :resource_unit, :resource_time, :resource_timezone, :payload ] end include Swagger::Blocks swagger_schema :MessageResponse do allOf do schema do key :'$ref', :MessageRequest end schema do property :id do key :type, :integer key :format, :int64 end property :created_at do key :type, :string key :format, :"date-time" end property :updated_at do key :type, :string key :format, :"date-time" end end end end swagger_schema :MessageRequest, required: [ :resource_uri, :resource_unit, :resource_time, :resource_timezone] do property :uuid do key :type, :string key :description, 'Universally Unique ID to be used to avoid duplicated messages' end property :resource_uri do key :type, :string key :description, 'URI of Resource' end property :resource_unit do key :type, :string key :description, 'Time unit of resource to monitor such as singular, daily, or hourly' end property :resource_time do key :type, :integer key :description, 'Time of Resource in unix timestamp such as 1476025200 (2016-10-10 in +09:00)' end property :resource_timezone do key :type, :string key :description, 'Timezone of resource time, that is, timezone of %Y-%m-%d for hdfs://path/to/%Y-%m-%d such as +09:00' end # Swagger supports only fixed data type, and does not support flexible json data type # To support flexible json type, we receive a json *string* and parse it in inside property :payload do key :type, :string key :description, 'Any json string' end end end
sonots/triglav
lib/triglav/error/invalid_authenticity_token.rb
module Triglav module Error class InvalidAuthenticityToken < Triglav::Error::StandardError def initialize @code = 401 @message = "Unauthenticated. Invalid or expired token." end end end end
exKAZUu/ParserTests
fixture/IronRuby/expected_xml/block.rb
<reponame>exKAZUu/ParserTests <block startline="1"> <lasgn startline="1"> <Symbol>i</Symbol> <lit startline="1"> <Fixnum>0</Fixnum> </lit> </lasgn> <if startline="3"> <call startline="3"> <lvar startline="3"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="4"> <lit startline="3"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block> <call startline="3"> <Nil /> <Symbol>p</Symbol> <arglist startline="3"> <lvar startline="3"> <Symbol>i</Symbol> </lvar> </arglist> </call> </block> <block /> </if> <if startline="4"> <call startline="4"> <lvar startline="4"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="4"> <lit startline="4"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block startline="4"> <call startline="4"> <Nil /> <Symbol>p</Symbol> <arglist startline="4"> <str startline="4"> <String>c</String> </str> </arglist> </call> <call startline="4"> <Nil /> <Symbol>p</Symbol> <arglist startline="4"> <str startline="4"> <String>c</String> </str> </arglist> </call> </block> <block /> </if> <if startline="5"> <call startline="5"> <lvar startline="5"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="5"> <lit startline="5"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block> <call startline="5"> <Nil /> <Symbol>p</Symbol> <arglist startline="5"> <str startline="5"> <String>c</String> </str> </arglist> </call> </block> <block /> </if> <if startline="6"> <call startline="6"> <lvar startline="6"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="6"> <lit startline="6"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block /> <block /> </if> <if startline="7"> <call startline="7"> <lvar startline="7"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="7"> <lit startline="7"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block startline="7"> <call startline="7"> <Nil /> <Symbol>p</Symbol> <arglist startline="7"> <str startline="7"> <String>c</String> </str> </arglist> </call> <call startline="7"> <Nil /> <Symbol>p</Symbol> <arglist startline="7"> <str startline="7"> <String>c</String> </str> </arglist> </call> </block> <block /> </if> <if startline="8"> <call startline="8"> <lvar startline="8"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="8"> <lit startline="8"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block> <call startline="8"> <Nil /> <Symbol>p</Symbol> <arglist startline="8"> <str startline="8"> <String>c</String> </str> </arglist> </call> </block> <block /> </if> <if startline="9"> <call startline="9"> <lvar startline="9"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="9"> <lit startline="9"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block /> <block /> </if> <if startline="10"> <call startline="10"> <lvar startline="10"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="11"> <lit startline="10"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block /> <block /> </if> <if startline="12"> <call startline="12"> <lvar startline="12"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="13"> <lit startline="12"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block /> <block /> </if> <if startline="15"> <call startline="15"> <lvar startline="15"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="16"> <lit startline="15"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block /> <block> <if startline="17"> <call startline="16"> <lvar startline="16"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="17"> <lit startline="16"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block /> <block /> </if> </block> </if> <if startline="18"> <call startline="18"> <lvar startline="18"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="19"> <lit startline="18"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block /> <block> <if startline="21"> <call startline="19"> <lvar startline="19"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="20"> <lit startline="19"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block /> <block /> </if> </block> </if> <if startline="24"> <call startline="24"> <lvar startline="24"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="25"> <lit startline="24"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block /> <block> <call startline="24"> <Nil /> <Symbol>p</Symbol> <arglist startline="24"> <lvar startline="24"> <Symbol>i</Symbol> </lvar> </arglist> </call> </block> </if> <if startline="25"> <call startline="25"> <lvar startline="25"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="25"> <lit startline="25"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block startline="25"> <call startline="25"> <Nil /> <Symbol>p</Symbol> <arglist startline="25"> <str startline="25"> <String>c</String> </str> </arglist> </call> <call startline="25"> <Nil /> <Symbol>p</Symbol> <arglist startline="25"> <str startline="25"> <String>c</String> </str> </arglist> </call> </block> <block /> </if> <if startline="26"> <call startline="26"> <lvar startline="26"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="26"> <lit startline="26"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block> <call startline="26"> <Nil /> <Symbol>p</Symbol> <arglist startline="26"> <str startline="26"> <String>c</String> </str> </arglist> </call> </block> <block /> </if> <if startline="27"> <call startline="27"> <lvar startline="27"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="27"> <lit startline="27"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block /> <block /> </if> <if startline="28"> <call startline="28"> <lvar startline="28"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="28"> <lit startline="28"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block startline="28"> <call startline="28"> <Nil /> <Symbol>p</Symbol> <arglist startline="28"> <str startline="28"> <String>c</String> </str> </arglist> </call> <call startline="28"> <Nil /> <Symbol>p</Symbol> <arglist startline="28"> <str startline="28"> <String>c</String> </str> </arglist> </call> </block> <block /> </if> <if startline="29"> <call startline="29"> <lvar startline="29"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="29"> <lit startline="29"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block> <call startline="29"> <Nil /> <Symbol>p</Symbol> <arglist startline="29"> <str startline="29"> <String>c</String> </str> </arglist> </call> </block> <block /> </if> <if startline="30"> <call startline="30"> <lvar startline="30"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="30"> <lit startline="30"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block /> <block /> </if> <if startline="32"> <call startline="31"> <lvar startline="31"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="32"> <lit startline="31"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block /> <block /> </if> <if startline="34"> <call startline="33"> <lvar startline="33"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="34"> <lit startline="33"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block /> <block /> </if> <case startline="38"> <lvar startline="38"> <Symbol>i</Symbol> </lvar> <when startline="38"> <array startline="39"> <lit startline="38"> <Fixnum>1</Fixnum> </lit> </array> <call startline="40"> <Nil /> <Symbol>p</Symbol> <arglist startline="40"> <str startline="39"> <String>1</String> </str> </arglist> </call> </when> <Nil /> </case> <case startline="43"> <lvar startline="43"> <Symbol>i</Symbol> </lvar> <when startline="43"> <array startline="44"> <lit startline="43"> <Fixnum>1</Fixnum> </lit> </array> <Nil /> </when> <Nil /> </case> <case startline="47"> <lvar startline="47"> <Symbol>i</Symbol> </lvar> <when startline="47"> <array startline="48"> <lit startline="47"> <Fixnum>1</Fixnum> </lit> </array> <call startline="49"> <Nil /> <Symbol>p</Symbol> <arglist startline="49"> <str startline="48"> <String>1</String> </str> </arglist> </call> </when> <when startline="49"> <array startline="50"> <lit startline="49"> <Fixnum>2</Fixnum> </lit> </array> <call startline="51"> <Nil /> <Symbol>p</Symbol> <arglist startline="51"> <str startline="50"> <String>1</String> </str> </arglist> </call> </when> <Nil /> </case> <case startline="54"> <lvar startline="54"> <Symbol>i</Symbol> </lvar> <when startline="54"> <array startline="55"> <lit startline="54"> <Fixnum>1</Fixnum> </lit> </array> <Nil /> </when> <when startline="55"> <array startline="56"> <lit startline="55"> <Fixnum>2</Fixnum> </lit> </array> <Nil /> </when> <Nil /> </case> <case startline="59"> <lvar startline="59"> <Symbol>i</Symbol> </lvar> <when startline="59"> <array startline="60"> <lit startline="59"> <Fixnum>1</Fixnum> </lit> </array> <call startline="61"> <Nil /> <Symbol>p</Symbol> <arglist startline="61"> <str startline="60"> <String>1</String> </str> </arglist> </call> </when> <when startline="61"> <array startline="62"> <lit startline="61"> <Fixnum>2</Fixnum> </lit> </array> <call startline="63"> <Nil /> <Symbol>p</Symbol> <arglist startline="63"> <str startline="62"> <String>2</String> </str> </arglist> </call> </when> <call startline="65"> <Nil /> <Symbol>p</Symbol> <arglist startline="65"> <str startline="64"> <String>else</String> </str> </arglist> </call> </case> <case startline="68"> <lvar startline="68"> <Symbol>i</Symbol> </lvar> <when startline="68"> <array startline="69"> <lit startline="68"> <Fixnum>1</Fixnum> </lit> </array> <Nil /> </when> <when startline="69"> <array startline="70"> <lit startline="69"> <Fixnum>2</Fixnum> </lit> </array> <Nil /> </when> <Nil /> </case> <case startline="74"> <Nil /> <when startline="74"> <array startline="75"> <call startline="74"> <lvar startline="74"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="75"> <lit startline="74"> <Fixnum>1</Fixnum> </lit> </arglist> </call> </array> <call startline="76"> <Nil /> <Symbol>p</Symbol> <arglist startline="76"> <str startline="75"> <String>1</String> </str> </arglist> </call> </when> <when startline="76"> <array startline="77"> <call startline="76"> <lvar startline="76"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="77"> <lit startline="76"> <Fixnum>2</Fixnum> </lit> </arglist> </call> </array> <call startline="78"> <Nil /> <Symbol>p</Symbol> <arglist startline="78"> <str startline="77"> <String>2</String> </str> </arglist> </call> </when> <call startline="80"> <Nil /> <Symbol>p</Symbol> <arglist startline="80"> <str startline="79"> <String>else</String> </str> </arglist> </call> </case> <case startline="83"> <Nil /> <when startline="83"> <array startline="83"> <call startline="83"> <lvar startline="83"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="83"> <lit startline="83"> <Fixnum>1</Fixnum> </lit> </arglist> </call> </array> <call startline="84"> <Nil /> <Symbol>p</Symbol> <arglist startline="84"> <str startline="83"> <String>1</String> </str> </arglist> </call> </when> <when startline="84"> <array startline="84"> <call startline="84"> <lvar startline="84"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="84"> <lit startline="84"> <Fixnum>2</Fixnum> </lit> </arglist> </call> </array> <call startline="85"> <Nil /> <Symbol>p</Symbol> <arglist startline="85"> <str startline="84"> <String>2</String> </str> </arglist> </call> </when> <call startline="86"> <Nil /> <Symbol>p</Symbol> <arglist startline="86"> <str startline="85"> <String>else</String> </str> </arglist> </call> </case> <call startline="89"> <Nil /> <Symbol>p</Symbol> <arglist startline="89"> <if startline="89"> <call startline="88"> <lvar startline="88"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="88"> <lit startline="88"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block> <str startline="88"> <String>0</String> </str> </block> <block> <str startline="88"> <String>1</String> </str> </block> </if> </arglist> </call> <until startline="91"> <call startline="91"> <lvar startline="91"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="91"> <lit startline="91"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block startline="91"> <call startline="91"> <Nil /> <Symbol>p</Symbol> <arglist startline="91"> <str startline="91"> <String>c</String> </str> </arglist> </call> <call startline="91"> <Nil /> <Symbol>p</Symbol> <arglist startline="91"> <str startline="91"> <String>c</String> </str> </arglist> </call> </block> <TrueClass>true</TrueClass> </until> <until startline="92"> <call startline="92"> <lvar startline="92"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="92"> <lit startline="92"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block> <call startline="92"> <Nil /> <Symbol>p</Symbol> <arglist startline="92"> <str startline="92"> <String>c</String> </str> </arglist> </call> </block> <TrueClass>true</TrueClass> </until> <until startline="93"> <call startline="93"> <lvar startline="93"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="93"> <lit startline="93"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block /> <TrueClass>true</TrueClass> </until> <until startline="94"> <call startline="94"> <lvar startline="94"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="94"> <lit startline="94"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block> <call startline="94"> <Nil /> <Symbol>p</Symbol> <arglist startline="94"> <str startline="94"> <String>c</String> </str> </arglist> </call> </block> <TrueClass>true</TrueClass> </until> <until startline="95"> <call startline="95"> <lvar startline="95"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="95"> <lit startline="95"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block /> <TrueClass>true</TrueClass> </until> <until startline="97"> <call startline="96"> <lvar startline="96"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="97"> <lit startline="96"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block /> <TrueClass>true</TrueClass> </until> <until startline="100"> <call startline="100"> <lvar startline="100"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="100"> <lit startline="100"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block startline="100"> <call startline="100"> <Nil /> <Symbol>p</Symbol> <arglist startline="100"> <str startline="100"> <String>c</String> </str> </arglist> </call> <call startline="100"> <Nil /> <Symbol>p</Symbol> <arglist startline="100"> <str startline="100"> <String>c</String> </str> </arglist> </call> </block> <TrueClass>true</TrueClass> </until> <until startline="101"> <call startline="101"> <lvar startline="101"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="101"> <lit startline="101"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block> <call startline="101"> <Nil /> <Symbol>p</Symbol> <arglist startline="101"> <str startline="101"> <String>c</String> </str> </arglist> </call> </block> <TrueClass>true</TrueClass> </until> <until startline="102"> <call startline="102"> <lvar startline="102"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="102"> <lit startline="102"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block /> <TrueClass>true</TrueClass> </until> <until startline="103"> <call startline="103"> <lvar startline="103"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="103"> <lit startline="103"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block> <call startline="103"> <Nil /> <Symbol>p</Symbol> <arglist startline="103"> <str startline="103"> <String>c</String> </str> </arglist> </call> </block> <TrueClass>true</TrueClass> </until> <until startline="104"> <call startline="104"> <lvar startline="104"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="104"> <lit startline="104"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block /> <TrueClass>true</TrueClass> </until> <until startline="105"> <call startline="105"> <lvar startline="105"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="106"> <lit startline="105"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block /> <TrueClass>true</TrueClass> </until> <for startline="109"> <array startline="109" /> <lasgn startline="109"> <Symbol>y</Symbol> </lasgn> <block startline="109"> <call startline="109"> <Nil /> <Symbol>p</Symbol> <arglist startline="109"> <str startline="109"> <String>c</String> </str> </arglist> </call> <call startline="109"> <Nil /> <Symbol>p</Symbol> <arglist startline="109"> <str startline="109"> <String>c</String> </str> </arglist> </call> </block> </for> <for startline="110"> <array startline="110" /> <lasgn startline="110"> <Symbol>y</Symbol> </lasgn> <block> <call startline="110"> <Nil /> <Symbol>p</Symbol> <arglist startline="110"> <str startline="110"> <String>c</String> </str> </arglist> </call> </block> </for> <for startline="111"> <array startline="111" /> <lasgn startline="111"> <Symbol>y</Symbol> </lasgn> <block /> </for> <for startline="112"> <array startline="112" /> <lasgn startline="112"> <Symbol>y</Symbol> </lasgn> <block> <call startline="112"> <Nil /> <Symbol>p</Symbol> <arglist startline="112"> <str startline="112"> <String>c</String> </str> </arglist> </call> </block> </for> <for startline="113"> <array startline="113" /> <lasgn startline="113"> <Symbol>y</Symbol> </lasgn> <block /> </for> <for startline="114"> <array startline="114" /> <lasgn startline="114"> <Symbol>y</Symbol> </lasgn> <block> <call startline="116"> <Nil /> <Symbol>p</Symbol> <arglist startline="116"> <str startline="115"> <String>c</String> </str> </arglist> </call> </block> </for> <for startline="117"> <array startline="117" /> <lasgn startline="117"> <Symbol>y</Symbol> </lasgn> <block /> </for> <iter startline="121"> <call startline="121"> <Nil /> <Symbol>loop</Symbol> <arglist startline="121" /> </call> <Nil /> <block startline="121"> <call startline="121"> <Nil /> <Symbol>p</Symbol> <arglist startline="121"> <str startline="121"> <String>c</String> </str> </arglist> </call> <call startline="121"> <Nil /> <Symbol>p</Symbol> <arglist startline="121"> <str startline="121"> <String>c</String> </str> </arglist> </call> </block> </iter> <iter startline="122"> <call startline="122"> <Nil /> <Symbol>loop</Symbol> <arglist startline="122" /> </call> <Nil /> <block> <call startline="122"> <Nil /> <Symbol>p</Symbol> <arglist startline="122"> <str startline="122"> <String>c</String> </str> </arglist> </call> </block> </iter> <iter startline="123"> <call startline="123"> <Nil /> <Symbol>loop</Symbol> <arglist startline="123" /> </call> <Nil /> <block /> </iter> <iter startline="124"> <call startline="124"> <Nil /> <Symbol>loop</Symbol> <arglist startline="124" /> </call> <Nil /> <block startline="124"> <call startline="124"> <Nil /> <Symbol>p</Symbol> <arglist startline="124"> <str startline="124"> <String>c</String> </str> </arglist> </call> <call startline="124"> <Nil /> <Symbol>p</Symbol> <arglist startline="124"> <str startline="124"> <String>c</String> </str> </arglist> </call> </block> </iter> <iter startline="125"> <call startline="125"> <Nil /> <Symbol>loop</Symbol> <arglist startline="125" /> </call> <Nil /> <block> <call startline="125"> <Nil /> <Symbol>p</Symbol> <arglist startline="125"> <str startline="125"> <String>c</String> </str> </arglist> </call> </block> </iter> <iter startline="126"> <call startline="126"> <Nil /> <Symbol>loop</Symbol> <arglist startline="126" /> </call> <Nil /> <block /> </iter> <defn startline="129"> <Symbol>a</Symbol> <args startline="129" /> <scope startline="129"> <block startline="129"> <call startline="129"> <Nil /> <Symbol>p</Symbol> <arglist startline="129"> <str startline="129"> <String>c</String> </str> </arglist> </call> <call startline="129"> <Nil /> <Symbol>p</Symbol> <arglist startline="129"> <str startline="129"> <String>c</String> </str> </arglist> </call> </block> </scope> </defn> <defn startline="130"> <Symbol>a</Symbol> <args startline="130" /> <scope startline="130"> <block startline="130"> <call startline="130"> <Nil /> <Symbol>p</Symbol> <arglist startline="130"> <str startline="130"> <String>c</String> </str> </arglist> </call> </block> </scope> </defn> <defn startline="131"> <Symbol>a</Symbol> <args startline="131" /> <scope startline="131"> <block startline="131"> <nil startline="131" /> </block> </scope> </defn> <iter startline="134"> <call startline="134"> <array startline="134" /> <Symbol>each</Symbol> <arglist startline="134" /> </call> <lasgn startline="134"> <Symbol>b</Symbol> </lasgn> <block startline="134"> <call startline="134"> <Nil /> <Symbol>p</Symbol> <arglist startline="134"> <lvar startline="134"> <Symbol>b</Symbol> </lvar> </arglist> </call> <call startline="134"> <Nil /> <Symbol>p</Symbol> <arglist startline="134"> <lvar startline="134"> <Symbol>b</Symbol> </lvar> </arglist> </call> </block> </iter> <iter startline="135"> <call startline="135"> <array startline="135" /> <Symbol>each</Symbol> <arglist startline="135" /> </call> <lasgn startline="135"> <Symbol>b</Symbol> </lasgn> <block> <call startline="135"> <Nil /> <Symbol>p</Symbol> <arglist startline="135"> <lvar startline="135"> <Symbol>b</Symbol> </lvar> </arglist> </call> </block> </iter> <iter startline="136"> <call startline="136"> <array startline="136" /> <Symbol>each</Symbol> <arglist startline="136" /> </call> <lasgn startline="136"> <Symbol>b</Symbol> </lasgn> <block /> </iter> <iter startline="137"> <call startline="137"> <array startline="137" /> <Symbol>each</Symbol> <arglist startline="137" /> </call> <Nil /> <block /> </iter> <iter startline="138"> <call startline="138"> <array startline="138" /> <Symbol>each</Symbol> <arglist startline="138" /> </call> <lasgn startline="138"> <Symbol>b</Symbol> </lasgn> <block> <call startline="138"> <Nil /> <Symbol>p</Symbol> <arglist startline="138"> <lvar startline="138"> <Symbol>b</Symbol> </lvar> </arglist> </call> </block> </iter> <iter startline="139"> <call startline="139"> <array startline="139" /> <Symbol>each</Symbol> <arglist startline="139" /> </call> <lasgn startline="139"> <Symbol>b</Symbol> </lasgn> <block /> </iter> <iter startline="140"> <call startline="140"> <array startline="140" /> <Symbol>each</Symbol> <arglist startline="140" /> </call> <Nil /> <block /> </iter> <iter startline="143"> <call startline="143"> <Nil /> <Symbol>lambda</Symbol> <arglist startline="143" /> </call> <masgn startline="143"> <array startline="143"> <lasgn startline="143"> <Symbol>x</Symbol> </lasgn> <lasgn startline="143"> <Symbol>y</Symbol> </lasgn> </array> </masgn> <block> <call startline="143"> <lvar startline="143"> <Symbol>x</Symbol> </lvar> <Symbol>+</Symbol> <arglist startline="143"> <lvar startline="143"> <Symbol>y</Symbol> </lvar> </arglist> </call> </block> </iter> <iter startline="144"> <call startline="144"> <Nil /> <Symbol>lambda</Symbol> <arglist startline="144" /> </call> <masgn startline="144"> <array startline="144"> <lasgn startline="144"> <Symbol>x</Symbol> </lasgn> <lasgn startline="144"> <Symbol>y</Symbol> </lasgn> </array> </masgn> <block /> </iter> <iter startline="145"> <call startline="145"> <Nil /> <Symbol>lambda</Symbol> <arglist startline="145" /> </call> <lasgn startline="145"> <Symbol>x</Symbol> </lasgn> <block> <call startline="145"> <lvar startline="145"> <Symbol>x</Symbol> </lvar> <Symbol>+</Symbol> <arglist startline="145"> <lit startline="145"> <Fixnum>1</Fixnum> </lit> </arglist> </call> </block> </iter> <iter startline="146"> <call startline="146"> <Nil /> <Symbol>lambda</Symbol> <arglist startline="146" /> </call> <lasgn startline="146"> <Symbol>x</Symbol> </lasgn> <block /> </iter> <iter startline="147"> <call startline="147"> <Nil /> <Symbol>lambda</Symbol> <arglist startline="147" /> </call> <Nil /> <block /> </iter> <iter startline="148"> <call startline="148"> <Nil /> <Symbol>lambda</Symbol> <arglist startline="148" /> </call> <lasgn startline="148"> <Symbol>x</Symbol> </lasgn> <block> <call startline="148"> <Nil /> <Symbol>p</Symbol> <arglist startline="148"> <call startline="148"> <lvar startline="148"> <Symbol>x</Symbol> </lvar> <Symbol>+</Symbol> <arglist startline="148"> <lit startline="148"> <Fixnum>1</Fixnum> </lit> </arglist> </call> </arglist> </call> </block> </iter> <iter startline="149"> <call startline="149"> <Nil /> <Symbol>lambda</Symbol> <arglist startline="149" /> </call> <lasgn startline="149"> <Symbol>x</Symbol> </lasgn> <block /> </iter> <iter startline="150"> <call startline="150"> <Nil /> <Symbol>lambda</Symbol> <arglist startline="150" /> </call> <Nil /> <block /> </iter> </block>
exKAZUu/ParserTests
fixture/Ruby19/input_code/Block1.rb
<reponame>exKAZUu/ParserTests i = 0 if i == 0 then p 'test' end unless i != 0 then p 'test' end case i when 0 p "test" end while i != 0 do p 'test' end until i == 0 do p 'test' end for y in [] do p 'test' end loop do p 'test' end loop { p 'test' } [].each do |b| p 'test' end [].each { |b| p 'test' } lambda do |x| p 'test' end lambda { |x| p 'test' }
exKAZUu/ParserTests
fixture/Ruby19/expected_xml/hierarchy.rb
<gh_stars>0 <block startline="1"> <class startline="1"> <Symbol>A</Symbol> <nil /> <defn startline="2"> <Symbol>a</Symbol> <args startline="3"></args> <nil startline="3"></nil> </defn> </class> <module startline="6"> <Symbol>B</Symbol> <defn startline="7"> <Symbol>b</Symbol> <args startline="8"></args> <nil startline="8"></nil> </defn> </module> <class startline="11"> <Symbol>C</Symbol> <nil /> <module startline="12"> <Symbol>CC</Symbol> <defn startline="13"> <Symbol>cc</Symbol> <args startline="14"></args> <nil startline="14"></nil> </defn> </module> </class> <sclass startline="18"> <const startline="18"> <Symbol>C</Symbol> </const> <defn startline="19"> <Symbol>c</Symbol> <args startline="20"></args> <nil startline="20"></nil> </defn> </sclass> <sclass startline="23"> <call startline="23"> <const startline="23"> <Symbol>C</Symbol> </const> <Symbol>new</Symbol> </call> <defn startline="24"> <Symbol>c2</Symbol> <args startline="25"></args> <nil startline="25"></nil> </defn> </sclass> <lasgn startline="28"> <Symbol>c3</Symbol> <call startline="28"> <const startline="28"> <Symbol>C</Symbol> </const> <Symbol>new</Symbol> </call> </lasgn> <sclass startline="29"> <lvar startline="29"> <Symbol>c3</Symbol> </lvar> </sclass> <defn startline="32"> <Symbol>z</Symbol> <args startline="33"></args> <nil startline="33"></nil> </defn> </block>
exKAZUu/ParserTests
fixture/Ruby19/input_code/hierarchy.rb
class A def a end end module B def b end end class C module CC def cc end end end class << C def c end end class << C.new def c2 end end c3 = C.new class << c3 end def z end
exKAZUu/ParserTests
fixture/Ruby19/expected_xml/ruby19.rb
<reponame>exKAZUu/ParserTests<gh_stars>0 <block startline="1"> <defn startline="1"> <Symbol>set_pixel</Symbol> <args startline="1"> <Symbol>h</Symbol> </args> <attrasgn startline="3"> <call startline="3"> <ivar startline="3"> <Symbol>@field</Symbol> </ivar> <Symbol>[]</Symbol> <call startline="3"> <lvar startline="3"> <Symbol>h</Symbol> </lvar> <Symbol>[]</Symbol> <lit startline="3"> <Symbol>y</Symbol> </lit> </call> </call> <Symbol>[]=</Symbol> <call startline="3"> <lvar startline="3"> <Symbol>h</Symbol> </lvar> <Symbol>[]</Symbol> <lit startline="3"> <Symbol>x</Symbol> </lit> </call> <call startline="3"> <lvar startline="3"> <Symbol>h</Symbol> </lvar> <Symbol>[]</Symbol> <lit startline="3"> <Symbol>color</Symbol> </lit> </call> </attrasgn> </defn> <call startline="7"> <nil /> <Symbol>set_pixel</Symbol> <hash startline="7"> <lit startline="7"> <Symbol>x</Symbol> </lit> <lit startline="7"> <Fixnum>30</Fixnum> </lit> <lit startline="7"> <Symbol>y</Symbol> </lit> <lit startline="7"> <Fixnum>50</Fixnum> </lit> <lit startline="7"> <Symbol>color</Symbol> </lit> <str startline="7"> <String>red</String> </str> </hash> </call> <call startline="8"> <nil /> <Symbol>set_pixel</Symbol> <hash startline="8"> <lit startline="8"> <Symbol>color</Symbol> </lit> <str startline="8"> <String>black</String> </str> <lit startline="8"> <Symbol>x</Symbol> </lit> <lit startline="8"> <Fixnum>40</Fixnum> </lit> <lit startline="8"> <Symbol>y</Symbol> </lit> <lit startline="8"> <Fixnum>50</Fixnum> </lit> </hash> </call> <defn startline="10"> <Symbol>foo</Symbol> <args startline="10"> <Symbol>a</Symbol> <Symbol>b</Symbol> <Symbol>*ary</Symbol> <Symbol>z</Symbol> </args> <call startline="11"> <nil /> <Symbol>p</Symbol> <array startline="11"> <lvar startline="11"> <Symbol>a</Symbol> </lvar> <lvar startline="11"> <Symbol>b</Symbol> </lvar> <lvar startline="11"> <Symbol>ary</Symbol> </lvar> <lvar startline="11"> <Symbol>z</Symbol> </lvar> </array> </call> </defn> <defn startline="14"> <Symbol>foo</Symbol> <args startline="14"> <Symbol>a</Symbol> <Symbol>b</Symbol> <Symbol>c</Symbol> <Symbol>d</Symbol> </args> <call startline="15"> <nil /> <Symbol>p</Symbol> <array startline="15"> <lvar startline="15"> <Symbol>a</Symbol> </lvar> <lvar startline="15"> <Symbol>b</Symbol> </lvar> <lvar startline="15"> <Symbol>c</Symbol> </lvar> <lvar startline="15"> <Symbol>d</Symbol> </lvar> </array> </call> </defn> <lasgn startline="18"> <Symbol>ary</Symbol> <array startline="18"> <lit startline="18"> <Fixnum>1</Fixnum> </lit> <lit startline="18"> <Fixnum>2</Fixnum> </lit> </array> </lasgn> <call startline="20"> <nil /> <Symbol>foo</Symbol> <splat startline="20"> <lvar startline="20"> <Symbol>ary</Symbol> </lvar> </splat> <splat startline="20"> <lvar startline="20"> <Symbol>ary</Symbol> </lvar> </splat> </call> <call startline="22"> <nil /> <Symbol>foo</Symbol> <lit startline="22"> <Fixnum>1</Fixnum> </lit> <lit startline="22"> <Fixnum>2</Fixnum> </lit> <lit startline="22"> <Fixnum>3</Fixnum> </lit> <lit startline="22"> <Fixnum>4</Fixnum> </lit> <lit startline="22"> <Fixnum>5</Fixnum> </lit> </call> <lasgn startline="24"> <Symbol>add_1</Symbol> <iter startline="24"> <call startline="24"> <nil /> <Symbol>lambda</Symbol> </call> <args startline="24"> <Symbol>x</Symbol> </args> <call startline="24"> <lvar startline="24"> <Symbol>x</Symbol> </lvar> <Symbol>+</Symbol> <lit startline="24"> <Fixnum>1</Fixnum> </lit> </call> </iter> </lasgn> <call startline="25"> <nil /> <Symbol>p</Symbol> <call startline="25"> <lvar startline="25"> <Symbol>add_1</Symbol> </lvar> <Symbol>call</Symbol> <lit startline="25"> <Fixnum>42</Fixnum> </lit> </call> </call> </block>
exKAZUu/ParserTests
fixture/Ruby19/input_code/fibonacci.rb
def fibonacci(n) if (n < 2) return n else return fibonacci(n - 1) + fibonacci(n - 2) end end
exKAZUu/ParserTests
fixture/Ruby18/input_code/coverage.rb
p(1, 2) if 1 == 1 p(2) end stmt(); p(1) if branch(1 == 1) stmt(); p(2) end
exKAZUu/ParserTests
fixture/Ruby19/expected_xml/prime.rb
<block startline="1"> <defn startline="1"> <Symbol>prime_table</Symbol> <args startline="1"> <Symbol>max</Symbol> </args> <lasgn startline="2"> <Symbol>result</Symbol> <call startline="2"> <const startline="2"> <Symbol>Array</Symbol> </const> <Symbol>new</Symbol> <call startline="2"> <lvar startline="2"> <Symbol>max</Symbol> </lvar> <Symbol>+</Symbol> <lit startline="2"> <Fixnum>1</Fixnum> </lit> </call> <true startline="2"></true> </call> </lasgn> <attrasgn startline="3"> <lvar startline="3"> <Symbol>result</Symbol> </lvar> <Symbol>[]=</Symbol> <lit startline="3"> <Fixnum>0</Fixnum> </lit> <attrasgn startline="3"> <lvar startline="3"> <Symbol>result</Symbol> </lvar> <Symbol>[]=</Symbol> <lit startline="3"> <Fixnum>1</Fixnum> </lit> <false startline="3"></false> </attrasgn> </attrasgn> <iter startline="4"> <call startline="4"> <dot2 startline="4"> <lit startline="4"> <Fixnum>2</Fixnum> </lit> <call startline="4"> <call startline="4"> <const startline="4"> <Symbol>Math</Symbol> </const> <Symbol>sqrt</Symbol> <lvar startline="4"> <Symbol>max</Symbol> </lvar> </call> <Symbol>ceil</Symbol> </call> </dot2> <Symbol>each</Symbol> </call> <args startline="4"> <Symbol>i</Symbol> </args> <block startline="5"> <if startline="5"> <call startline="5"> <lvar startline="5"> <Symbol>result</Symbol> </lvar> <Symbol>[]</Symbol> <lvar startline="5"> <Symbol>i</Symbol> </lvar> </call> <nil /> <next startline="5"></next> </if> <iter startline="6"> <call startline="6"> <call startline="6"> <lvar startline="6"> <Symbol>i</Symbol> </lvar> <Symbol>*</Symbol> <lit startline="6"> <Fixnum>2</Fixnum> </lit> </call> <Symbol>step</Symbol> <lvar startline="6"> <Symbol>max</Symbol> </lvar> <lvar startline="6"> <Symbol>i</Symbol> </lvar> </call> <args startline="6"> <Symbol>j</Symbol> </args> <attrasgn startline="7"> <lvar startline="7"> <Symbol>result</Symbol> </lvar> <Symbol>[]=</Symbol> <lvar startline="7"> <Symbol>j</Symbol> </lvar> <false startline="7"></false> </attrasgn> </iter> </block> </iter> <lvar startline="10"> <Symbol>result</Symbol> </lvar> </defn> <defn startline="13"> <Symbol>prime_list</Symbol> <args startline="13"> <Symbol>table</Symbol> </args> <lasgn startline="14"> <Symbol>result</Symbol> <array startline="14"></array> </lasgn> <iter startline="15"> <call startline="15"> <lvar startline="15"> <Symbol>table</Symbol> </lvar> <Symbol>each_with_index</Symbol> </call> <args startline="15"> <Symbol>b</Symbol> <Symbol>i</Symbol> </args> <if startline="16"> <lvar startline="16"> <Symbol>b</Symbol> </lvar> <call startline="16"> <lvar startline="16"> <Symbol>result</Symbol> </lvar> <Symbol>&lt;&lt;</Symbol> <lvar startline="16"> <Symbol>i</Symbol> </lvar> </call> <nil /> </if> </iter> <lvar startline="18"> <Symbol>result</Symbol> </lvar> </defn> <defn startline="21"> <Symbol>prime_check_table</Symbol> <args startline="21"> <Symbol>min</Symbol> <Symbol>max</Symbol> <Symbol>primes</Symbol> </args> <lasgn startline="22"> <Symbol>result</Symbol> <call startline="22"> <const startline="22"> <Symbol>Array</Symbol> </const> <Symbol>new</Symbol> <call startline="22"> <call startline="22"> <lvar startline="22"> <Symbol>max</Symbol> </lvar> <Symbol>-</Symbol> <lvar startline="22"> <Symbol>min</Symbol> </lvar> </call> <Symbol>+</Symbol> <lit startline="22"> <Fixnum>1</Fixnum> </lit> </call> <true startline="22"></true> </call> </lasgn> <if startline="23"> <call startline="23"> <lvar startline="23"> <Symbol>min</Symbol> </lvar> <Symbol>==</Symbol> <lit startline="23"> <Fixnum>1</Fixnum> </lit> </call> <attrasgn startline="23"> <lvar startline="23"> <Symbol>result</Symbol> </lvar> <Symbol>[]=</Symbol> <lit startline="23"> <Fixnum>0</Fixnum> </lit> <false startline="23"></false> </attrasgn> <nil /> </if> <lasgn startline="24"> <Symbol>maxsq</Symbol> <call startline="24"> <call startline="24"> <const startline="24"> <Symbol>Math</Symbol> </const> <Symbol>sqrt</Symbol> <lvar startline="24"> <Symbol>max</Symbol> </lvar> </call> <Symbol>ceil</Symbol> </call> </lasgn> <lasgn startline="25"> <Symbol>i</Symbol> <lit startline="25"> <Fixnum>1</Fixnum> </lit> </lasgn> <while startline="26"> <call startline="26"> <lasgn startline="26"> <Symbol>p</Symbol> <call startline="26"> <lvar startline="26"> <Symbol>primes</Symbol> </lvar> <Symbol>[]</Symbol> <lvar startline="26"> <Symbol>i</Symbol> </lvar> </call> </lasgn> <Symbol>&lt;=</Symbol> <lvar startline="26"> <Symbol>maxsq</Symbol> </lvar> </call> <block startline="27"> <iter startline="27"> <call startline="27"> <call startline="27"> <call startline="27"> <call startline="27"> <lvar startline="27"> <Symbol>min</Symbol> </lvar> <Symbol>+</Symbol> <lvar startline="27"> <Symbol>p</Symbol> </lvar> </call> <Symbol>-</Symbol> <lit startline="27"> <Fixnum>1</Fixnum> </lit> </call> <Symbol>-</Symbol> <call startline="27"> <call startline="27"> <call startline="27"> <lvar startline="27"> <Symbol>min</Symbol> </lvar> <Symbol>+</Symbol> <lvar startline="27"> <Symbol>p</Symbol> </lvar> </call> <Symbol>-</Symbol> <lit startline="27"> <Fixnum>1</Fixnum> </lit> </call> <Symbol>%</Symbol> <lvar startline="27"> <Symbol>p</Symbol> </lvar> </call> </call> <Symbol>step</Symbol> <lvar startline="27"> <Symbol>max</Symbol> </lvar> <lvar startline="27"> <Symbol>p</Symbol> </lvar> </call> <args startline="27"> <Symbol>j</Symbol> </args> <attrasgn startline="28"> <lvar startline="28"> <Symbol>result</Symbol> </lvar> <Symbol>[]=</Symbol> <call startline="28"> <lvar startline="28"> <Symbol>j</Symbol> </lvar> <Symbol>-</Symbol> <lvar startline="28"> <Symbol>min</Symbol> </lvar> </call> <false startline="28"></false> </attrasgn> </iter> <lasgn startline="30"> <Symbol>i</Symbol> <call startline="30"> <lvar startline="30"> <Symbol>i</Symbol> </lvar> <Symbol>+</Symbol> <lit startline="30"> <Fixnum>1</Fixnum> </lit> </call> </lasgn> </block> <TrueClass>true</TrueClass> </while> <return startline="32"> <lvar startline="32"> <Symbol>result</Symbol> </lvar> </return> </defn> <defn startline="35"> <Symbol>show_primes</Symbol> <args startline="35"> <Symbol>min</Symbol> <Symbol>offset</Symbol> <Symbol>max</Symbol> <Symbol>table</Symbol> </args> <while startline="36"> <call startline="36"> <lvar startline="36"> <Symbol>min</Symbol> </lvar> <Symbol>&lt;=</Symbol> <lvar startline="36"> <Symbol>max</Symbol> </lvar> </call> <block startline="37"> <if startline="37"> <call startline="37"> <lvar startline="37"> <Symbol>table</Symbol> </lvar> <Symbol>[]</Symbol> <lvar startline="37"> <Symbol>min</Symbol> </lvar> </call> <call startline="37"> <nil /> <Symbol>puts</Symbol> <call startline="37"> <lvar startline="37"> <Symbol>min</Symbol> </lvar> <Symbol>+</Symbol> <lvar startline="37"> <Symbol>offset</Symbol> </lvar> </call> </call> <nil /> </if> <lasgn startline="38"> <Symbol>min</Symbol> <call startline="38"> <lvar startline="38"> <Symbol>min</Symbol> </lvar> <Symbol>+</Symbol> <lit startline="38"> <Fixnum>2</Fixnum> </lit> </call> </lasgn> </block> <TrueClass>true</TrueClass> </while> </defn> <if startline="42"> <call startline="42"> <str startline="42"> <String>(string)</String> </str> <Symbol>==</Symbol> <gvar startline="42"> <Symbol>$0</Symbol> </gvar> </call> <block startline="43"> <lasgn startline="43"> <Symbol>max_prime</Symbol> <lit startline="43"> <Fixnum>50000</Fixnum> </lit> </lasgn> <lasgn startline="44"> <Symbol>table</Symbol> <call startline="44"> <nil /> <Symbol>prime_table</Symbol> <lvar startline="44"> <Symbol>max_prime</Symbol> </lvar> </call> </lasgn> <lasgn startline="45"> <Symbol>primes</Symbol> <call startline="45"> <nil /> <Symbol>prime_list</Symbol> <lvar startline="45"> <Symbol>table</Symbol> </lvar> </call> </lasgn> <call startline="46"> <lvar startline="46"> <Symbol>primes</Symbol> </lvar> <Symbol>&lt;&lt;</Symbol> <lit startline="46"> <Fixnum>1000000000</Fixnum> </lit> </call> <iter startline="48"> <call startline="48"> <call startline="48"> <call startline="48"> <call startline="48"> <nil /> <Symbol>gets</Symbol> </call> <Symbol>chomp</Symbol> </call> <Symbol>to_i</Symbol> </call> <Symbol>times</Symbol> </call> <args startline="48"> <Symbol>i</Symbol> </args> <block startline="49"> <if startline="49"> <call startline="49"> <lvar startline="49"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <lit startline="49"> <Fixnum>0</Fixnum> </lit> </call> <nil /> <call startline="49"> <nil /> <Symbol>puts</Symbol> </call> </if> <masgn startline="50"> <array startline="50"> <lasgn startline="50"> <Symbol>min</Symbol> </lasgn> <lasgn startline="50"> <Symbol>max</Symbol> </lasgn> </array> <to_ary startline="51"> <iter startline="50"> <call startline="50"> <call startline="50"> <call startline="50"> <nil /> <Symbol>gets</Symbol> </call> <Symbol>split</Symbol> </call> <Symbol>map</Symbol> </call> <args startline="50"> <Symbol>s</Symbol> </args> <call startline="50"> <lvar startline="50"> <Symbol>s</Symbol> </lvar> <Symbol>to_i</Symbol> </call> </iter> </to_ary> </masgn> <if startline="51"> <call startline="51"> <lvar startline="51"> <Symbol>min</Symbol> </lvar> <Symbol>&lt;=</Symbol> <lit startline="51"> <Fixnum>2</Fixnum> </lit> </call> <call startline="51"> <nil /> <Symbol>puts</Symbol> <lit startline="51"> <Fixnum>2</Fixnum> </lit> </call> <nil /> </if> <if startline="53"> <call startline="53"> <call startline="53"> <lvar startline="53"> <Symbol>min</Symbol> </lvar> <Symbol>&amp;</Symbol> <lit startline="53"> <Fixnum>1</Fixnum> </lit> </call> <Symbol>==</Symbol> <lit startline="53"> <Fixnum>0</Fixnum> </lit> </call> <lasgn startline="53"> <Symbol>min</Symbol> <call startline="53"> <lvar startline="53"> <Symbol>min</Symbol> </lvar> <Symbol>+</Symbol> <lit startline="53"> <Fixnum>1</Fixnum> </lit> </call> </lasgn> <nil /> </if> <if startline="54"> <call startline="54"> <call startline="54"> <lvar startline="54"> <Symbol>max</Symbol> </lvar> <Symbol>&amp;</Symbol> <lit startline="54"> <Fixnum>1</Fixnum> </lit> </call> <Symbol>==</Symbol> <lit startline="54"> <Fixnum>0</Fixnum> </lit> </call> <lasgn startline="54"> <Symbol>max</Symbol> <call startline="54"> <lvar startline="54"> <Symbol>max</Symbol> </lvar> <Symbol>-</Symbol> <lit startline="54"> <Fixnum>1</Fixnum> </lit> </call> </lasgn> <nil /> </if> <if startline="56"> <call startline="56"> <lvar startline="56"> <Symbol>max</Symbol> </lvar> <Symbol>&lt;=</Symbol> <lvar startline="56"> <Symbol>max_prime</Symbol> </lvar> </call> <call startline="57"> <nil /> <Symbol>show_primes</Symbol> <lvar startline="57"> <Symbol>min</Symbol> </lvar> <lit startline="57"> <Fixnum>0</Fixnum> </lit> <lvar startline="57"> <Symbol>max</Symbol> </lvar> <lvar startline="57"> <Symbol>table</Symbol> </lvar> </call> <block startline="59"> <if startline="59"> <call startline="59"> <lvar startline="59"> <Symbol>min</Symbol> </lvar> <Symbol>&lt;=</Symbol> <lvar startline="59"> <Symbol>max_prime</Symbol> </lvar> </call> <block startline="60"> <call startline="60"> <nil /> <Symbol>show_primes</Symbol> <lvar startline="60"> <Symbol>min</Symbol> </lvar> <lit startline="60"> <Fixnum>0</Fixnum> </lit> <lvar startline="60"> <Symbol>max_prime</Symbol> </lvar> <lvar startline="60"> <Symbol>table</Symbol> </lvar> </call> <lasgn startline="61"> <Symbol>min</Symbol> <call startline="61"> <lvar startline="61"> <Symbol>max_prime</Symbol> </lvar> <Symbol>+</Symbol> <lit startline="61"> <Fixnum>1</Fixnum> </lit> </call> </lasgn> <if startline="62"> <call startline="62"> <call startline="62"> <lvar startline="62"> <Symbol>min</Symbol> </lvar> <Symbol>&amp;</Symbol> <lit startline="62"> <Fixnum>1</Fixnum> </lit> </call> <Symbol>==</Symbol> <lit startline="62"> <Fixnum>0</Fixnum> </lit> </call> <lasgn startline="62"> <Symbol>min</Symbol> <call startline="62"> <lvar startline="62"> <Symbol>min</Symbol> </lvar> <Symbol>+</Symbol> <lit startline="62"> <Fixnum>1</Fixnum> </lit> </call> </lasgn> <nil /> </if> </block> <nil /> </if> <lasgn startline="64"> <Symbol>result</Symbol> <call startline="64"> <nil /> <Symbol>prime_check_table</Symbol> <lvar startline="64"> <Symbol>min</Symbol> </lvar> <lvar startline="64"> <Symbol>max</Symbol> </lvar> <lvar startline="64"> <Symbol>primes</Symbol> </lvar> </call> </lasgn> <call startline="65"> <nil /> <Symbol>show_primes</Symbol> <lit startline="65"> <Fixnum>0</Fixnum> </lit> <lvar startline="65"> <Symbol>min</Symbol> </lvar> <call startline="65"> <lvar startline="65"> <Symbol>max</Symbol> </lvar> <Symbol>-</Symbol> <lvar startline="65"> <Symbol>min</Symbol> </lvar> </call> <lvar startline="65"> <Symbol>result</Symbol> </lvar> </call> </block> </if> </block> </iter> </block> <nil /> </if> <lasgn startline="70"> <Symbol>x</Symbol> <lit startline="70"> <Fixnum>1</Fixnum> </lit> </lasgn> <case startline="71"> <lvar startline="71"> <Symbol>x</Symbol> </lvar> <when startline="72"> <array startline="73"> <lit startline="72"> <Fixnum>1</Fixnum> </lit> </array> <call startline="73"> <nil /> <Symbol>p</Symbol> <str startline="73"> <String>1</String> </str> </call> </when> <when startline="74"> <array startline="75"> <lit startline="74"> <Fixnum>2</Fixnum> </lit> </array> <call startline="75"> <nil /> <Symbol>p</Symbol> <str startline="75"> <String>2</String> </str> </call> </when> <call startline="77"> <nil /> <Symbol>p</Symbol> <str startline="77"> <String>else</String> </str> </call> </case> <if startline="82"> <call startline="80"> <lvar startline="80"> <Symbol>x</Symbol> </lvar> <Symbol>==</Symbol> <lit startline="80"> <Fixnum>1</Fixnum> </lit> </call> <str startline="80"> <String>a</String> </str> <str startline="80"> <String>b</String> </str> </if> <while startline="82"> <call startline="82"> <lvar startline="82"> <Symbol>x</Symbol> </lvar> <Symbol>&gt;=</Symbol> <lit startline="82"> <Fixnum>0</Fixnum> </lit> </call> <block startline="82"> <call startline="82"> <nil /> <Symbol>p</Symbol> <str startline="82"> <String>a</String> </str> </call> <call startline="82"> <nil /> <Symbol>p</Symbol> <str startline="82"> <String>a</String> </str> </call> </block> <TrueClass>true</TrueClass> </while> <while startline="83"> <call startline="83"> <lvar startline="83"> <Symbol>x</Symbol> </lvar> <Symbol>&gt;=</Symbol> <lit startline="83"> <Fixnum>0</Fixnum> </lit> </call> <call startline="83"> <nil /> <Symbol>p</Symbol> <str startline="83"> <String>a</String> </str> </call> <TrueClass>true</TrueClass> </while> <until startline="85"> <call startline="85"> <lvar startline="85"> <Symbol>x</Symbol> </lvar> <Symbol>&lt;</Symbol> <lit startline="85"> <Fixnum>0</Fixnum> </lit> </call> <call startline="86"> <nil /> <Symbol>p</Symbol> <str startline="86"> <String>a</String> </str> </call> <TrueClass>true</TrueClass> </until> <for startline="89"> <array startline="89"></array> <lasgn startline="89"> <Symbol>y</Symbol> </lasgn> <call startline="90"> <nil /> <Symbol>p</Symbol> <str startline="90"> <String>c</String> </str> </call> </for> <defn startline="93"> <Symbol>a</Symbol> <args startline="93"></args> <call startline="94"> <nil /> <Symbol>p</Symbol> <str startline="94"> <String>c</String> </str> </call> </defn> <iter startline="97"> <call startline="97"> <array startline="97"></array> <Symbol>each</Symbol> </call> <args startline="97"> <Symbol>b</Symbol> </args> <call startline="98"> <nil /> <Symbol>p</Symbol> <lvar startline="98"> <Symbol>b</Symbol> </lvar> </call> </iter> <iter startline="101"> <call startline="101"> <array startline="101"></array> <Symbol>each</Symbol> </call> <args startline="101"> <Symbol>b</Symbol> </args> <call startline="102"> <nil /> <Symbol>p</Symbol> <lvar startline="102"> <Symbol>b</Symbol> </lvar> </call> </iter> </block>
exKAZUu/ParserTests
fixture/Ruby19/expected_xml/fibonacci.rb
<gh_stars>0 <defn startline="1"> <Symbol>fibonacci</Symbol> <args startline="1"> <Symbol>n</Symbol> </args> <if startline="2"> <call startline="2"> <lvar startline="2"> <Symbol>n</Symbol> </lvar> <Symbol>&lt;</Symbol> <lit startline="2"> <Fixnum>2</Fixnum> </lit> </call> <return startline="3"> <lvar startline="3"> <Symbol>n</Symbol> </lvar> </return> <return startline="5"> <call startline="5"> <call startline="5"> <nil /> <Symbol>fibonacci</Symbol> <call startline="5"> <lvar startline="5"> <Symbol>n</Symbol> </lvar> <Symbol>-</Symbol> <lit startline="5"> <Fixnum>1</Fixnum> </lit> </call> </call> <Symbol>+</Symbol> <call startline="5"> <nil /> <Symbol>fibonacci</Symbol> <call startline="5"> <lvar startline="5"> <Symbol>n</Symbol> </lvar> <Symbol>-</Symbol> <lit startline="5"> <Fixnum>2</Fixnum> </lit> </call> </call> </call> </return> </if> </defn>
exKAZUu/ParserTests
fixture/Ruby19/input_code/student.rb
<reponame>exKAZUu/ParserTests class Student def initialize(name) @name = name end def name() @name end end students = Array.new(2) students[0] = Student.new('Tom') students[1] = Student.new('Anna') for student in students puts student.name end
exKAZUu/ParserTests
fixture/Ruby19/expected_xml/Block3.rb
<block startline="1"> <lasgn startline="1"> <Symbol>i</Symbol> <lit startline="1"> <Fixnum>0</Fixnum> </lit> </lasgn> <if startline="3"> <call startline="3"> <lvar startline="3"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <lit startline="3"> <Fixnum>0</Fixnum> </lit> </call> <nil /> <nil /> </if> <if startline="4"> <call startline="4"> <lvar startline="4"> <Symbol>i</Symbol> </lvar> <Symbol>!=</Symbol> <lit startline="4"> <Fixnum>0</Fixnum> </lit> </call> <nil /> <nil /> </if> <case startline="6"> <lvar startline="6"> <Symbol>i</Symbol> </lvar> <when startline="7"> <array startline="8"> <lit startline="7"> <Fixnum>0</Fixnum> </lit> </array> <call startline="8"> <nil /> <Symbol>p</Symbol> <str startline="8"> <String>test</String> </str> </call> </when> <nil /> </case> <while startline="11"> <call startline="11"> <lvar startline="11"> <Symbol>i</Symbol> </lvar> <Symbol>!=</Symbol> <lit startline="11"> <Fixnum>0</Fixnum> </lit> </call> <nil /> <TrueClass>true</TrueClass> </while> <until startline="12"> <call startline="12"> <lvar startline="12"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <lit startline="12"> <Fixnum>0</Fixnum> </lit> </call> <nil /> <TrueClass>true</TrueClass> </until> <for startline="13"> <array startline="13"></array> <lasgn startline="13"> <Symbol>y</Symbol> </lasgn> </for> <iter startline="14"> <call startline="14"> <nil /> <Symbol>loop</Symbol> </call> <args startline="14"></args> </iter> <iter startline="15"> <call startline="15"> <nil /> <Symbol>loop</Symbol> </call> <args startline="15"></args> </iter> <iter startline="16"> <call startline="16"> <array startline="16"></array> <Symbol>each</Symbol> </call> <args startline="16"> <Symbol>b</Symbol> </args> </iter> <iter startline="17"> <call startline="17"> <array startline="17"></array> <Symbol>each</Symbol> </call> <args startline="17"> <Symbol>b</Symbol> </args> </iter> <iter startline="18"> <call startline="18"> <nil /> <Symbol>lambda</Symbol> </call> <args startline="18"> <Symbol>x</Symbol> </args> </iter> <iter startline="19"> <call startline="19"> <nil /> <Symbol>lambda</Symbol> </call> <args startline="19"> <Symbol>x</Symbol> </args> </iter> <lasgn startline="21"> <Symbol>i</Symbol> <lit startline="21"> <Fixnum>0</Fixnum> </lit> </lasgn> <if startline="23"> <call startline="23"> <lvar startline="23"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <lit startline="23"> <Fixnum>0</Fixnum> </lit> </call> <nil /> <nil /> </if> <if startline="26"> <call startline="26"> <lvar startline="26"> <Symbol>i</Symbol> </lvar> <Symbol>!=</Symbol> <lit startline="26"> <Fixnum>0</Fixnum> </lit> </call> <nil /> <nil /> </if> <case startline="29"> <lvar startline="29"> <Symbol>i</Symbol> </lvar> <when startline="30"> <array startline="31"> <lit startline="30"> <Fixnum>0</Fixnum> </lit> </array> <nil /> </when> <nil /> </case> <while startline="33"> <call startline="33"> <lvar startline="33"> <Symbol>i</Symbol> </lvar> <Symbol>!=</Symbol> <lit startline="33"> <Fixnum>0</Fixnum> </lit> </call> <nil /> <TrueClass>true</TrueClass> </while> <until startline="36"> <call startline="36"> <lvar startline="36"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <lit startline="36"> <Fixnum>0</Fixnum> </lit> </call> <nil /> <TrueClass>true</TrueClass> </until> <for startline="39"> <array startline="39"></array> <lasgn startline="39"> <Symbol>y</Symbol> </lasgn> </for> <iter startline="42"> <call startline="42"> <nil /> <Symbol>loop</Symbol> </call> <args startline="43"></args> </iter> <iter startline="45"> <call startline="45"> <nil /> <Symbol>loop</Symbol> </call> <args startline="46"></args> </iter> <iter startline="48"> <call startline="48"> <array startline="48"></array> <Symbol>each</Symbol> </call> <args startline="48"> <Symbol>b</Symbol> </args> </iter> <iter startline="51"> <call startline="51"> <array startline="51"></array> <Symbol>each</Symbol> </call> <args startline="51"> <Symbol>b</Symbol> </args> </iter> <iter startline="54"> <call startline="54"> <nil /> <Symbol>lambda</Symbol> </call> <args startline="54"> <Symbol>x</Symbol> </args> </iter> <iter startline="57"> <call startline="57"> <nil /> <Symbol>lambda</Symbol> </call> <args startline="57"> <Symbol>x</Symbol> </args> </iter> </block>
exKAZUu/ParserTests
fixture/Ruby18/expected_xml/block.rb
<gh_stars>0 <block startline="1"> <lasgn startline="1"> <Symbol>i</Symbol> <lit startline="1"> <Fixnum>0</Fixnum> </lit> </lasgn> <if startline="5"> <call startline="5"> <lvar startline="5"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <lit startline="5"> <Fixnum>0</Fixnum> </lit> </call> <call startline="5"> <nil /> <Symbol>p</Symbol> <lvar startline="5"> <Symbol>i</Symbol> </lvar> </call> <nil /> </if> <if startline="6"> <call startline="6"> <lvar startline="6"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <lit startline="6"> <Fixnum>0</Fixnum> </lit> </call> <block startline="6"> <call startline="6"> <nil /> <Symbol>p</Symbol> <str startline="6"> <String>c</String> </str> </call> <call startline="6"> <nil /> <Symbol>p</Symbol> <str startline="6"> <String>c</String> </str> </call> </block> <nil /> </if> <if startline="7"> <call startline="7"> <lvar startline="7"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <lit startline="7"> <Fixnum>0</Fixnum> </lit> </call> <call startline="7"> <nil /> <Symbol>p</Symbol> <str startline="7"> <String>c</String> </str> </call> <nil /> </if> <if startline="8"> <call startline="8"> <lvar startline="8"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <lit startline="8"> <Fixnum>0</Fixnum> </lit> </call> <nil /> <nil /> </if> <if startline="9"> <call startline="9"> <lvar startline="9"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <lit startline="9"> <Fixnum>0</Fixnum> </lit> </call> <block startline="9"> <call startline="9"> <nil /> <Symbol>p</Symbol> <str startline="9"> <String>c</String> </str> </call> <call startline="9"> <nil /> <Symbol>p</Symbol> <str startline="9"> <String>c</String> </str> </call> </block> <nil /> </if> <if startline="10"> <call startline="10"> <lvar startline="10"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <lit startline="10"> <Fixnum>0</Fixnum> </lit> </call> <call startline="10"> <nil /> <Symbol>p</Symbol> <str startline="10"> <String>c</String> </str> </call> <nil /> </if> <if startline="11"> <call startline="11"> <lvar startline="11"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <lit startline="11"> <Fixnum>0</Fixnum> </lit> </call> <nil /> <nil /> </if> <if startline="12"> <call startline="12"> <lvar startline="12"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <lit startline="12"> <Fixnum>0</Fixnum> </lit> </call> <nil /> <nil /> </if> <if startline="14"> <call startline="14"> <lvar startline="14"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <lit startline="14"> <Fixnum>0</Fixnum> </lit> </call> <nil /> <nil /> </if> <if startline="17"> <call startline="17"> <lvar startline="17"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <lit startline="17"> <Fixnum>0</Fixnum> </lit> </call> <nil /> <if startline="19"> <call startline="18"> <lvar startline="18"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <lit startline="18"> <Fixnum>0</Fixnum> </lit> </call> <nil /> <nil /> </if> </if> <if startline="20"> <call startline="20"> <lvar startline="20"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <lit startline="20"> <Fixnum>0</Fixnum> </lit> </call> <nil /> <if startline="23"> <call startline="21"> <lvar startline="21"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <lit startline="21"> <Fixnum>0</Fixnum> </lit> </call> <nil /> <nil /> </if> </if> <if startline="26"> <call startline="26"> <lvar startline="26"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <lit startline="26"> <Fixnum>0</Fixnum> </lit> </call> <nil /> <call startline="26"> <nil /> <Symbol>p</Symbol> <lvar startline="26"> <Symbol>i</Symbol> </lvar> </call> </if> <if startline="27"> <call startline="27"> <lvar startline="27"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <lit startline="27"> <Fixnum>0</Fixnum> </lit> </call> <block startline="27"> <call startline="27"> <nil /> <Symbol>p</Symbol> <str startline="27"> <String>c</String> </str> </call> <call startline="27"> <nil /> <Symbol>p</Symbol> <str startline="27"> <String>c</String> </str> </call> </block> <nil /> </if> <if startline="28"> <call startline="28"> <lvar startline="28"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <lit startline="28"> <Fixnum>0</Fixnum> </lit> </call> <call startline="28"> <nil /> <Symbol>p</Symbol> <str startline="28"> <String>c</String> </str> </call> <nil /> </if> <if startline="29"> <call startline="29"> <lvar startline="29"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <lit startline="29"> <Fixnum>0</Fixnum> </lit> </call> <nil /> <nil /> </if> <if startline="30"> <call startline="30"> <lvar startline="30"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <lit startline="30"> <Fixnum>0</Fixnum> </lit> </call> <block startline="30"> <call startline="30"> <nil /> <Symbol>p</Symbol> <str startline="30"> <String>c</String> </str> </call> <call startline="30"> <nil /> <Symbol>p</Symbol> <str startline="30"> <String>c</String> </str> </call> </block> <nil /> </if> <if startline="31"> <call startline="31"> <lvar startline="31"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <lit startline="31"> <Fixnum>0</Fixnum> </lit> </call> <call startline="31"> <nil /> <Symbol>p</Symbol> <str startline="31"> <String>c</String> </str> </call> <nil /> </if> <if startline="32"> <call startline="32"> <lvar startline="32"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <lit startline="32"> <Fixnum>0</Fixnum> </lit> </call> <nil /> <nil /> </if> <if startline="34"> <call startline="33"> <lvar startline="33"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <lit startline="33"> <Fixnum>0</Fixnum> </lit> </call> <nil /> <nil /> </if> <if startline="36"> <call startline="35"> <lvar startline="35"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <lit startline="35"> <Fixnum>0</Fixnum> </lit> </call> <nil /> <nil /> </if> <case startline="39"> <lvar startline="39"> <Symbol>i</Symbol> </lvar> <when startline="40"> <array startline="41"> <lit startline="40"> <Fixnum>1</Fixnum> </lit> </array> <call startline="41"> <nil /> <Symbol>p</Symbol> <str startline="41"> <String>1</String> </str> </call> </when> <nil /> </case> <case startline="44"> <lvar startline="44"> <Symbol>i</Symbol> </lvar> <when startline="45"> <array startline="46"> <lit startline="45"> <Fixnum>1</Fixnum> </lit> </array> <nil /> </when> <nil /> </case> <case startline="48"> <lvar startline="48"> <Symbol>i</Symbol> </lvar> <when startline="49"> <array startline="50"> <lit startline="49"> <Fixnum>1</Fixnum> </lit> </array> <call startline="50"> <nil /> <Symbol>p</Symbol> <str startline="50"> <String>1</String> </str> </call> </when> <when startline="51"> <array startline="52"> <lit startline="51"> <Fixnum>2</Fixnum> </lit> </array> <call startline="52"> <nil /> <Symbol>p</Symbol> <str startline="52"> <String>1</String> </str> </call> </when> <nil /> </case> <case startline="55"> <lvar startline="55"> <Symbol>i</Symbol> </lvar> <when startline="56"> <array startline="57"> <lit startline="56"> <Fixnum>1</Fixnum> </lit> </array> <nil /> </when> <when startline="57"> <array startline="58"> <lit startline="57"> <Fixnum>2</Fixnum> </lit> </array> <nil /> </when> <nil /> </case> <case startline="60"> <lvar startline="60"> <Symbol>i</Symbol> </lvar> <when startline="61"> <array startline="62"> <lit startline="61"> <Fixnum>1</Fixnum> </lit> </array> <call startline="62"> <nil /> <Symbol>p</Symbol> <str startline="62"> <String>1</String> </str> </call> </when> <when startline="63"> <array startline="64"> <lit startline="63"> <Fixnum>2</Fixnum> </lit> </array> <call startline="64"> <nil /> <Symbol>p</Symbol> <str startline="64"> <String>2</String> </str> </call> </when> <call startline="66"> <nil /> <Symbol>p</Symbol> <str startline="66"> <String>else</String> </str> </call> </case> <case startline="69"> <lvar startline="69"> <Symbol>i</Symbol> </lvar> <when startline="70"> <array startline="71"> <lit startline="70"> <Fixnum>1</Fixnum> </lit> </array> <nil /> </when> <when startline="71"> <array startline="72"> <lit startline="71"> <Fixnum>2</Fixnum> </lit> </array> <nil /> </when> <nil /> </case> <case startline="76"> <nil /> <when startline="76"> <array startline="77"> <call startline="76"> <lvar startline="76"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <lit startline="76"> <Fixnum>1</Fixnum> </lit> </call> </array> <call startline="77"> <nil /> <Symbol>p</Symbol> <str startline="77"> <String>1</String> </str> </call> </when> <when startline="78"> <array startline="79"> <call startline="78"> <lvar startline="78"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <lit startline="78"> <Fixnum>2</Fixnum> </lit> </call> </array> <call startline="79"> <nil /> <Symbol>p</Symbol> <str startline="79"> <String>2</String> </str> </call> </when> <call startline="81"> <nil /> <Symbol>p</Symbol> <str startline="81"> <String>else</String> </str> </call> </case> <case startline="85"> <nil /> <when startline="85"> <array startline="85"> <call startline="85"> <lvar startline="85"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <lit startline="85"> <Fixnum>1</Fixnum> </lit> </call> </array> <call startline="85"> <nil /> <Symbol>p</Symbol> <str startline="85"> <String>1</String> </str> </call> </when> <when startline="86"> <array startline="86"> <call startline="86"> <lvar startline="86"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <lit startline="86"> <Fixnum>2</Fixnum> </lit> </call> </array> <call startline="86"> <nil /> <Symbol>p</Symbol> <str startline="86"> <String>2</String> </str> </call> </when> <call startline="87"> <nil /> <Symbol>p</Symbol> <str startline="87"> <String>else</String> </str> </call> </case> <call startline="93"> <nil /> <Symbol>p</Symbol> <if startline="93"> <call startline="90"> <lvar startline="90"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <lit startline="90"> <Fixnum>0</Fixnum> </lit> </call> <str startline="90"> <String>0</String> </str> <str startline="90"> <String>1</String> </str> </if> </call> <until startline="93"> <call startline="93"> <lvar startline="93"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <lit startline="93"> <Fixnum>0</Fixnum> </lit> </call> <block startline="93"> <call startline="93"> <nil /> <Symbol>p</Symbol> <str startline="93"> <String>c</String> </str> </call> <call startline="93"> <nil /> <Symbol>p</Symbol> <str startline="93"> <String>c</String> </str> </call> </block> <TrueClass>true</TrueClass> </until> <until startline="94"> <call startline="94"> <lvar startline="94"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <lit startline="94"> <Fixnum>0</Fixnum> </lit> </call> <call startline="94"> <nil /> <Symbol>p</Symbol> <str startline="94"> <String>c</String> </str> </call> <TrueClass>true</TrueClass> </until> <until startline="95"> <call startline="95"> <lvar startline="95"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <lit startline="95"> <Fixnum>0</Fixnum> </lit> </call> <nil /> <TrueClass>true</TrueClass> </until> <until startline="96"> <call startline="96"> <lvar startline="96"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <lit startline="96"> <Fixnum>0</Fixnum> </lit> </call> <call startline="96"> <nil /> <Symbol>p</Symbol> <str startline="96"> <String>c</String> </str> </call> <TrueClass>true</TrueClass> </until> <until startline="97"> <call startline="97"> <lvar startline="97"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <lit startline="97"> <Fixnum>0</Fixnum> </lit> </call> <nil /> <TrueClass>true</TrueClass> </until> <until startline="99"> <call startline="98"> <lvar startline="98"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <lit startline="98"> <Fixnum>0</Fixnum> </lit> </call> <nil /> <TrueClass>true</TrueClass> </until> <until startline="102"> <call startline="102"> <lvar startline="102"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <lit startline="102"> <Fixnum>0</Fixnum> </lit> </call> <block startline="102"> <call startline="102"> <nil /> <Symbol>p</Symbol> <str startline="102"> <String>c</String> </str> </call> <call startline="102"> <nil /> <Symbol>p</Symbol> <str startline="102"> <String>c</String> </str> </call> </block> <TrueClass>true</TrueClass> </until> <until startline="103"> <call startline="103"> <lvar startline="103"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <lit startline="103"> <Fixnum>0</Fixnum> </lit> </call> <call startline="103"> <nil /> <Symbol>p</Symbol> <str startline="103"> <String>c</String> </str> </call> <TrueClass>true</TrueClass> </until> <until startline="104"> <call startline="104"> <lvar startline="104"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <lit startline="104"> <Fixnum>0</Fixnum> </lit> </call> <nil /> <TrueClass>true</TrueClass> </until> <until startline="105"> <call startline="105"> <lvar startline="105"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <lit startline="105"> <Fixnum>0</Fixnum> </lit> </call> <call startline="105"> <nil /> <Symbol>p</Symbol> <str startline="105"> <String>c</String> </str> </call> <TrueClass>true</TrueClass> </until> <until startline="106"> <call startline="106"> <lvar startline="106"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <lit startline="106"> <Fixnum>0</Fixnum> </lit> </call> <nil /> <TrueClass>true</TrueClass> </until> <until startline="107"> <call startline="107"> <lvar startline="107"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <lit startline="107"> <Fixnum>0</Fixnum> </lit> </call> <nil /> <TrueClass>true</TrueClass> </until> <for startline="111"> <array startline="111"></array> <lasgn startline="111"> <Symbol>y</Symbol> </lasgn> <block startline="111"> <call startline="111"> <nil /> <Symbol>p</Symbol> <str startline="111"> <String>c</String> </str> </call> <call startline="111"> <nil /> <Symbol>p</Symbol> <str startline="111"> <String>c</String> </str> </call> </block> </for> <for startline="112"> <array startline="112"></array> <lasgn startline="112"> <Symbol>y</Symbol> </lasgn> <call startline="112"> <nil /> <Symbol>p</Symbol> <str startline="112"> <String>c</String> </str> </call> </for> <for startline="113"> <array startline="113"></array> <lasgn startline="113"> <Symbol>y</Symbol> </lasgn> </for> <for startline="114"> <array startline="114"></array> <lasgn startline="114"> <Symbol>y</Symbol> </lasgn> <call startline="114"> <nil /> <Symbol>p</Symbol> <str startline="114"> <String>c</String> </str> </call> </for> <for startline="115"> <array startline="115"></array> <lasgn startline="115"> <Symbol>y</Symbol> </lasgn> </for> <for startline="116"> <array startline="116"></array> <lasgn startline="116"> <Symbol>y</Symbol> </lasgn> <call startline="117"> <nil /> <Symbol>p</Symbol> <str startline="117"> <String>c</String> </str> </call> </for> <for startline="119"> <array startline="119"></array> <lasgn startline="119"> <Symbol>y</Symbol> </lasgn> </for> <iter startline="123"> <call startline="123"> <nil /> <Symbol>loop</Symbol> </call> <args startline="123"></args> <block startline="123"> <call startline="123"> <nil /> <Symbol>p</Symbol> <str startline="123"> <String>c</String> </str> </call> <call startline="123"> <nil /> <Symbol>p</Symbol> <str startline="123"> <String>c</String> </str> </call> </block> </iter> <iter startline="124"> <call startline="124"> <nil /> <Symbol>loop</Symbol> </call> <args startline="124"></args> <call startline="124"> <nil /> <Symbol>p</Symbol> <str startline="124"> <String>c</String> </str> </call> </iter> <iter startline="125"> <call startline="125"> <nil /> <Symbol>loop</Symbol> </call> <args startline="125"></args> </iter> <iter startline="126"> <call startline="126"> <nil /> <Symbol>loop</Symbol> </call> <args startline="126"></args> <block startline="126"> <call startline="126"> <nil /> <Symbol>p</Symbol> <str startline="126"> <String>c</String> </str> </call> <call startline="126"> <nil /> <Symbol>p</Symbol> <str startline="126"> <String>c</String> </str> </call> </block> </iter> <iter startline="127"> <call startline="127"> <nil /> <Symbol>loop</Symbol> </call> <args startline="127"></args> <call startline="127"> <nil /> <Symbol>p</Symbol> <str startline="127"> <String>c</String> </str> </call> </iter> <iter startline="128"> <call startline="128"> <nil /> <Symbol>loop</Symbol> </call> <args startline="128"></args> </iter> <defn startline="131"> <Symbol>a</Symbol> <args startline="131"></args> <call startline="131"> <nil /> <Symbol>p</Symbol> <str startline="131"> <String>c</String> </str> </call> <call startline="131"> <nil /> <Symbol>p</Symbol> <str startline="131"> <String>c</String> </str> </call> </defn> <defn startline="132"> <Symbol>a</Symbol> <args startline="132"></args> <call startline="132"> <nil /> <Symbol>p</Symbol> <str startline="132"> <String>c</String> </str> </call> </defn> <defn startline="133"> <Symbol>a</Symbol> <args startline="133"></args> <nil startline="133"></nil> </defn> <iter startline="136"> <call startline="136"> <array startline="136"></array> <Symbol>each</Symbol> </call> <args startline="136"> <Symbol>b</Symbol> </args> <block startline="136"> <call startline="136"> <nil /> <Symbol>p</Symbol> <lvar startline="136"> <Symbol>b</Symbol> </lvar> </call> <call startline="136"> <nil /> <Symbol>p</Symbol> <lvar startline="136"> <Symbol>b</Symbol> </lvar> </call> </block> </iter> <iter startline="137"> <call startline="137"> <array startline="137"></array> <Symbol>each</Symbol> </call> <args startline="137"> <Symbol>b</Symbol> </args> <call startline="137"> <nil /> <Symbol>p</Symbol> <lvar startline="137"> <Symbol>b</Symbol> </lvar> </call> </iter> <iter startline="138"> <call startline="138"> <array startline="138"></array> <Symbol>each</Symbol> </call> <args startline="138"> <Symbol>b</Symbol> </args> </iter> <iter startline="139"> <call startline="139"> <array startline="139"></array> <Symbol>each</Symbol> </call> <args startline="139"></args> </iter> <iter startline="140"> <call startline="140"> <array startline="140"></array> <Symbol>each</Symbol> </call> <args startline="140"> <Symbol>b</Symbol> </args> <call startline="140"> <nil /> <Symbol>p</Symbol> <lvar startline="140"> <Symbol>b</Symbol> </lvar> </call> </iter> <iter startline="141"> <call startline="141"> <array startline="141"></array> <Symbol>each</Symbol> </call> <args startline="141"> <Symbol>b</Symbol> </args> </iter> <iter startline="142"> <call startline="142"> <array startline="142"></array> <Symbol>each</Symbol> </call> <args startline="142"></args> </iter> <iter startline="145"> <call startline="145"> <nil /> <Symbol>lambda</Symbol> </call> <args startline="145"> <Symbol>x</Symbol> <Symbol>y</Symbol> </args> <call startline="145"> <lvar startline="145"> <Symbol>x</Symbol> </lvar> <Symbol>+</Symbol> <lvar startline="145"> <Symbol>y</Symbol> </lvar> </call> </iter> <iter startline="146"> <call startline="146"> <nil /> <Symbol>lambda</Symbol> </call> <args startline="146"> <Symbol>x</Symbol> <Symbol>y</Symbol> </args> </iter> <iter startline="147"> <call startline="147"> <nil /> <Symbol>lambda</Symbol> </call> <args startline="147"> <Symbol>x</Symbol> </args> <call startline="147"> <lvar startline="147"> <Symbol>x</Symbol> </lvar> <Symbol>+</Symbol> <lit startline="147"> <Fixnum>1</Fixnum> </lit> </call> </iter> <iter startline="148"> <call startline="148"> <nil /> <Symbol>lambda</Symbol> </call> <args startline="148"> <Symbol>x</Symbol> </args> </iter> <iter startline="149"> <call startline="149"> <nil /> <Symbol>lambda</Symbol> </call> <args startline="149"></args> </iter> <iter startline="150"> <call startline="150"> <nil /> <Symbol>lambda</Symbol> </call> <args startline="150"> <Symbol>x</Symbol> </args> <call startline="150"> <nil /> <Symbol>p</Symbol> <call startline="150"> <lvar startline="150"> <Symbol>x</Symbol> </lvar> <Symbol>+</Symbol> <lit startline="150"> <Fixnum>1</Fixnum> </lit> </call> </call> </iter> <iter startline="151"> <call startline="151"> <nil /> <Symbol>lambda</Symbol> </call> <args startline="151"> <Symbol>x</Symbol> </args> </iter> <iter startline="152"> <call startline="152"> <nil /> <Symbol>lambda</Symbol> </call> <args startline="152"></args> </iter> </block>
exKAZUu/ParserTests
fixture/Ruby18/input_code/block.rb
i = 0 ; ; p i if i == 0 if i == 0 then p 'c'; p 'c'; end if i == 0 then p 'c' end if i == 0 then end if i == 0; p 'c'; p 'c'; end if i == 0; p 'c' end if i == 0; end if i == 0 end if i == 0 else end if i == 0 elsif i == 0 end if i == 0 elsif i == 0 else end p i unless i == 0 unless i != 0 then p 'c'; p 'c'; end unless i != 0 then p 'c' end unless i != 0 then end unless i != 0; p 'c'; p 'c'; end unless i != 0; p 'c' end unless i != 0; end unless i != 0 end unless i != 0 else end case i when 1 p "1" end case i when 1 end case i when 1 p "1" when 2 p "1" end case i when 1 when 2 end case i when 1 p "1" when 2 p "2" else p "else" end case i when 1 when 2 else end case when i == 1 p "1" when i == 2 p "2" else p "else" end case when i == 1 then p "1" when i == 2 ; p "2" else p "else" end p i == 0 ? "0" : "1" while i != 0 do p 'c'; p 'c'; end while i != 0 do p 'c' end while i != 0 do end while i != 0; p 'c' end while i != 0; end while i != 0 end until i == 0 do p 'c'; p 'c'; end until i == 0 do p 'c' end until i == 0 do end until i == 0; p 'c' end until i == 0; end until i == 0 end for y in [] do p 'c'; p 'c'; end for y in [] do p 'c' end for y in [] do end for y in []; p 'c' end for y in []; end for y in [] p 'c' end for y in [] end loop do p 'c'; p 'c'; end loop do p 'c' end loop do end loop { p 'c'; p 'c'; } loop { p 'c' } loop { } def a() p 'c'; p 'c'; end def a() p 'c' end def a() end [].each { |b| p b; p b; } [].each { |b| p b } [].each { |b| } [].each { } [].each do |b| p b end [].each do |b| end [].each do end lambda { |x,y| x + y } lambda { |x,y| } lambda { |x| x + 1 } lambda { |x| } lambda {} lambda do |x| p x + 1 end lambda do |x| end lambda do end
exKAZUu/ParserTests
fixture/Ruby19/input_code/Block2.rb
<reponame>exKAZUu/ParserTests<filename>fixture/Ruby19/input_code/Block2.rb i = 0 if i == 0 then p 'test' end unless i != 0 then p 'test' end case i when 0 p "test" end while i != 0 do p 'test' end until i == 0 do p 'test' end for y in [] do p 'test' end loop do p 'test' end loop { p 'test' } [].each do |b| p 'test' end [].each { |b| p 'test' } lambda do |x| p 'test' end lambda { |x| p 'test' }
exKAZUu/ParserTests
fixture/Ruby19/input_code/Block4.rb
i = 0 if i == 0 then end unless i != 0 then end case i when 0 p "test" end while i != 0 do p "test" end until i == 0 do p "test" end for y in [] do p "test" end loop do p "test" end loop { p "test" } [].each do |b| p "test" end [].each { |b| p "test" } lambda do |x| p "test" end lambda { |x| p "test" } i = 0 if i == 0 then p "test" end unless i != 0 then p "test" end case i when 0 p "test" end while i != 0 do p "test" end until i == 0 do p "test" end for y in [] do p "test" end loop do p "test" end loop { p "test" } [].each do |b| p "test" end [].each { |b| p "test" } lambda do |x| p "test" end lambda { |x| p "test" }
exKAZUu/ParserTests
fixture/Ruby19/expected_xml/Block1.rb
<block startline="1"> <lasgn startline="1"> <Symbol>i</Symbol> <lit startline="1"> <Fixnum>0</Fixnum> </lit> </lasgn> <if startline="3"> <call startline="3"> <lvar startline="3"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <lit startline="3"> <Fixnum>0</Fixnum> </lit> </call> <call startline="3"> <nil /> <Symbol>p</Symbol> <str startline="3"> <String>test</String> </str> </call> <nil /> </if> <if startline="4"> <call startline="4"> <lvar startline="4"> <Symbol>i</Symbol> </lvar> <Symbol>!=</Symbol> <lit startline="4"> <Fixnum>0</Fixnum> </lit> </call> <nil /> <call startline="4"> <nil /> <Symbol>p</Symbol> <str startline="4"> <String>test</String> </str> </call> </if> <case startline="6"> <lvar startline="6"> <Symbol>i</Symbol> </lvar> <when startline="7"> <array startline="8"> <lit startline="7"> <Fixnum>0</Fixnum> </lit> </array> <call startline="8"> <nil /> <Symbol>p</Symbol> <str startline="8"> <String>test</String> </str> </call> </when> <nil /> </case> <while startline="11"> <call startline="11"> <lvar startline="11"> <Symbol>i</Symbol> </lvar> <Symbol>!=</Symbol> <lit startline="11"> <Fixnum>0</Fixnum> </lit> </call> <call startline="11"> <nil /> <Symbol>p</Symbol> <str startline="11"> <String>test</String> </str> </call> <TrueClass>true</TrueClass> </while> <until startline="12"> <call startline="12"> <lvar startline="12"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <lit startline="12"> <Fixnum>0</Fixnum> </lit> </call> <call startline="12"> <nil /> <Symbol>p</Symbol> <str startline="12"> <String>test</String> </str> </call> <TrueClass>true</TrueClass> </until> <for startline="13"> <array startline="13"></array> <lasgn startline="13"> <Symbol>y</Symbol> </lasgn> <call startline="13"> <nil /> <Symbol>p</Symbol> <str startline="13"> <String>test</String> </str> </call> </for> <iter startline="14"> <call startline="14"> <nil /> <Symbol>loop</Symbol> </call> <args startline="14"></args> <call startline="14"> <nil /> <Symbol>p</Symbol> <str startline="14"> <String>test</String> </str> </call> </iter> <iter startline="15"> <call startline="15"> <nil /> <Symbol>loop</Symbol> </call> <args startline="15"></args> <call startline="15"> <nil /> <Symbol>p</Symbol> <str startline="15"> <String>test</String> </str> </call> </iter> <iter startline="16"> <call startline="16"> <array startline="16"></array> <Symbol>each</Symbol> </call> <args startline="16"> <Symbol>b</Symbol> </args> <call startline="16"> <nil /> <Symbol>p</Symbol> <str startline="16"> <String>test</String> </str> </call> </iter> <iter startline="17"> <call startline="17"> <array startline="17"></array> <Symbol>each</Symbol> </call> <args startline="17"> <Symbol>b</Symbol> </args> <call startline="17"> <nil /> <Symbol>p</Symbol> <str startline="17"> <String>test</String> </str> </call> </iter> <iter startline="18"> <call startline="18"> <nil /> <Symbol>lambda</Symbol> </call> <args startline="18"> <Symbol>x</Symbol> </args> <call startline="18"> <nil /> <Symbol>p</Symbol> <str startline="18"> <String>test</String> </str> </call> </iter> <iter startline="19"> <call startline="19"> <nil /> <Symbol>lambda</Symbol> </call> <args startline="19"> <Symbol>x</Symbol> </args> <call startline="19"> <nil /> <Symbol>p</Symbol> <str startline="19"> <String>test</String> </str> </call> </iter> </block>
exKAZUu/ParserTests
fixture/IronRuby/expected_xml/Block3.rb
<filename>fixture/IronRuby/expected_xml/Block3.rb <block startline="1"> <lasgn startline="1"> <Symbol>i</Symbol> <lit startline="1"> <Fixnum>0</Fixnum> </lit> </lasgn> <if startline="3"> <call startline="3"> <lvar startline="3"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="3"> <lit startline="3"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block /> <block /> </if> <if startline="4"> <call startline="4"> <lvar startline="4"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="4"> <lit startline="4"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block /> <block /> </if> <case startline="7"> <lvar startline="7"> <Symbol>i</Symbol> </lvar> <when startline="7"> <array startline="8"> <lit startline="7"> <Fixnum>0</Fixnum> </lit> </array> <call startline="9"> <Nil /> <Symbol>p</Symbol> <arglist startline="9"> <str startline="8"> <String>test</String> </str> </arglist> </call> </when> <Nil /> </case> <until startline="11"> <call startline="11"> <lvar startline="11"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="11"> <lit startline="11"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block /> <TrueClass>true</TrueClass> </until> <until startline="12"> <call startline="12"> <lvar startline="12"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="12"> <lit startline="12"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block /> <TrueClass>true</TrueClass> </until> <for startline="13"> <array startline="13" /> <lasgn startline="13"> <Symbol>y</Symbol> </lasgn> <block /> </for> <iter startline="14"> <call startline="14"> <Nil /> <Symbol>loop</Symbol> <arglist startline="14" /> </call> <Nil /> <block /> </iter> <iter startline="15"> <call startline="15"> <Nil /> <Symbol>loop</Symbol> <arglist startline="15" /> </call> <Nil /> <block /> </iter> <iter startline="16"> <call startline="16"> <array startline="16" /> <Symbol>each</Symbol> <arglist startline="16" /> </call> <lasgn startline="16"> <Symbol>b</Symbol> </lasgn> <block /> </iter> <iter startline="17"> <call startline="17"> <array startline="17" /> <Symbol>each</Symbol> <arglist startline="17" /> </call> <lasgn startline="17"> <Symbol>b</Symbol> </lasgn> <block /> </iter> <iter startline="18"> <call startline="18"> <Nil /> <Symbol>lambda</Symbol> <arglist startline="18" /> </call> <lasgn startline="18"> <Symbol>x</Symbol> </lasgn> <block /> </iter> <iter startline="19"> <call startline="19"> <Nil /> <Symbol>lambda</Symbol> <arglist startline="19" /> </call> <lasgn startline="19"> <Symbol>x</Symbol> </lasgn> <block /> </iter> <lasgn startline="21"> <Symbol>i</Symbol> <lit startline="21"> <Fixnum>0</Fixnum> </lit> </lasgn> <if startline="23"> <call startline="23"> <lvar startline="23"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="23"> <lit startline="23"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block /> <block /> </if> <if startline="26"> <call startline="26"> <lvar startline="26"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="26"> <lit startline="26"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block /> <block /> </if> <case startline="30"> <lvar startline="30"> <Symbol>i</Symbol> </lvar> <when startline="30"> <array startline="31"> <lit startline="30"> <Fixnum>0</Fixnum> </lit> </array> <Nil /> </when> <Nil /> </case> <until startline="33"> <call startline="33"> <lvar startline="33"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="33"> <lit startline="33"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block /> <TrueClass>true</TrueClass> </until> <until startline="36"> <call startline="36"> <lvar startline="36"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="36"> <lit startline="36"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block /> <TrueClass>true</TrueClass> </until> <for startline="39"> <array startline="39" /> <lasgn startline="39"> <Symbol>y</Symbol> </lasgn> <block /> </for> <iter startline="42"> <call startline="43"> <Nil /> <Symbol>loop</Symbol> <arglist startline="43" /> </call> <Nil /> <block /> </iter> <iter startline="45"> <call startline="46"> <Nil /> <Symbol>loop</Symbol> <arglist startline="46" /> </call> <Nil /> <block /> </iter> <iter startline="48"> <call startline="48"> <array startline="48" /> <Symbol>each</Symbol> <arglist startline="48" /> </call> <lasgn startline="48"> <Symbol>b</Symbol> </lasgn> <block /> </iter> <iter startline="51"> <call startline="51"> <array startline="51" /> <Symbol>each</Symbol> <arglist startline="51" /> </call> <lasgn startline="51"> <Symbol>b</Symbol> </lasgn> <block /> </iter> <iter startline="54"> <call startline="55"> <Nil /> <Symbol>lambda</Symbol> <arglist startline="55" /> </call> <lasgn startline="54"> <Symbol>x</Symbol> </lasgn> <block /> </iter> <iter startline="57"> <call startline="58"> <Nil /> <Symbol>lambda</Symbol> <arglist startline="58" /> </call> <lasgn startline="57"> <Symbol>x</Symbol> </lasgn> <block /> </iter> </block>
exKAZUu/ParserTests
fixture/IronRuby/expected_xml/Block2.rb
<block startline="1"> <lasgn startline="1"> <Symbol>i</Symbol> <lit startline="1"> <Fixnum>0</Fixnum> </lit> </lasgn> <if startline="3"> <call startline="3"> <lvar startline="3"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="3"> <lit startline="3"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block> <call startline="5"> <Nil /> <Symbol>p</Symbol> <arglist startline="5"> <str startline="4"> <String>test</String> </str> </arglist> </call> </block> <block /> </if> <if startline="6"> <call startline="6"> <lvar startline="6"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="6"> <lit startline="6"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block> <call startline="8"> <Nil /> <Symbol>p</Symbol> <arglist startline="8"> <str startline="7"> <String>test</String> </str> </arglist> </call> </block> <block /> </if> <case startline="11"> <lvar startline="11"> <Symbol>i</Symbol> </lvar> <when startline="11"> <array startline="12"> <lit startline="11"> <Fixnum>0</Fixnum> </lit> </array> <call startline="13"> <Nil /> <Symbol>p</Symbol> <arglist startline="13"> <str startline="12"> <String>test</String> </str> </arglist> </call> </when> <Nil /> </case> <until startline="15"> <call startline="15"> <lvar startline="15"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="15"> <lit startline="15"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block> <call startline="17"> <Nil /> <Symbol>p</Symbol> <arglist startline="17"> <str startline="16"> <String>test</String> </str> </arglist> </call> </block> <TrueClass>true</TrueClass> </until> <until startline="19"> <call startline="19"> <lvar startline="19"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="19"> <lit startline="19"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block> <call startline="21"> <Nil /> <Symbol>p</Symbol> <arglist startline="21"> <str startline="20"> <String>test</String> </str> </arglist> </call> </block> <TrueClass>true</TrueClass> </until> <for startline="23"> <array startline="23" /> <lasgn startline="23"> <Symbol>y</Symbol> </lasgn> <block> <call startline="25"> <Nil /> <Symbol>p</Symbol> <arglist startline="25"> <str startline="24"> <String>test</String> </str> </arglist> </call> </block> </for> <iter startline="27"> <call startline="29"> <Nil /> <Symbol>loop</Symbol> <arglist startline="29" /> </call> <Nil /> <block> <call startline="29"> <Nil /> <Symbol>p</Symbol> <arglist startline="29"> <str startline="28"> <String>test</String> </str> </arglist> </call> </block> </iter> <iter startline="31"> <call startline="33"> <Nil /> <Symbol>loop</Symbol> <arglist startline="33" /> </call> <Nil /> <block> <call startline="33"> <Nil /> <Symbol>p</Symbol> <arglist startline="33"> <str startline="32"> <String>test</String> </str> </arglist> </call> </block> </iter> <iter startline="35"> <call startline="35"> <array startline="35" /> <Symbol>each</Symbol> <arglist startline="35" /> </call> <lasgn startline="35"> <Symbol>b</Symbol> </lasgn> <block> <call startline="37"> <Nil /> <Symbol>p</Symbol> <arglist startline="37"> <str startline="36"> <String>test</String> </str> </arglist> </call> </block> </iter> <iter startline="39"> <call startline="39"> <array startline="39" /> <Symbol>each</Symbol> <arglist startline="39" /> </call> <lasgn startline="39"> <Symbol>b</Symbol> </lasgn> <block> <call startline="41"> <Nil /> <Symbol>p</Symbol> <arglist startline="41"> <str startline="40"> <String>test</String> </str> </arglist> </call> </block> </iter> <iter startline="43"> <call startline="45"> <Nil /> <Symbol>lambda</Symbol> <arglist startline="45" /> </call> <lasgn startline="43"> <Symbol>x</Symbol> </lasgn> <block> <call startline="45"> <Nil /> <Symbol>p</Symbol> <arglist startline="45"> <str startline="44"> <String>test</String> </str> </arglist> </call> </block> </iter> <iter startline="47"> <call startline="49"> <Nil /> <Symbol>lambda</Symbol> <arglist startline="49" /> </call> <lasgn startline="47"> <Symbol>x</Symbol> </lasgn> <block> <call startline="49"> <Nil /> <Symbol>p</Symbol> <arglist startline="49"> <str startline="48"> <String>test</String> </str> </arglist> </call> </block> </iter> </block>
exKAZUu/ParserTests
fixture/IronRuby/expected_xml/ruby2ruby_test.rb
<reponame>exKAZUu/ParserTests <block startline="1"> <lasgn startline="1"> <Symbol>i</Symbol> <lit startline="1"> <Fixnum>0</Fixnum> </lit> </lasgn> <if startline="2"> <call startline="2"> <lvar startline="2"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="2"> <lit startline="2"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block> <call startline="3"> <Nil /> <Symbol>p</Symbol> <arglist startline="3"> <lvar startline="3"> <Symbol>i</Symbol> </lvar> </arglist> </call> </block> <block /> </if> </block>
exKAZUu/ParserTests
fixture/Ruby19/expected_xml/sjis.rb
<filename>fixture/Ruby19/expected_xml/sjis.rb <call startline="1"> <nil /> <Symbol>p</Symbol> <str startline="1"> <String>“ú–{Œêƒ\ƒ“‰Â•\</String> </str> </call>
exKAZUu/ParserTests
fixture/Ruby19/input_code/Block3.rb
i = 0 if i == 0 then end unless i != 0 then end case i when 0 p "test" end while i != 0 do end until i == 0 do end for y in [] do end loop do end loop { } [].each do |b| end [].each { |b| } lambda do |x| end lambda { |x| } i = 0 if i == 0 then end unless i != 0 then end case i when 0 end while i != 0 do end until i == 0 do end for y in [] do end loop do end loop { } [].each do |b| end [].each { |b| } lambda do |x| end lambda { |x| }
exKAZUu/ParserTests
fixture/IronRuby/expected_xml/Block4.rb
<gh_stars>0 <block startline="1"> <lasgn startline="1"> <Symbol>i</Symbol> <lit startline="1"> <Fixnum>0</Fixnum> </lit> </lasgn> <if startline="3"> <call startline="3"> <lvar startline="3"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="3"> <lit startline="3"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block /> <block /> </if> <if startline="4"> <call startline="4"> <lvar startline="4"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="4"> <lit startline="4"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block /> <block /> </if> <case startline="7"> <lvar startline="7"> <Symbol>i</Symbol> </lvar> <when startline="7"> <array startline="8"> <lit startline="7"> <Fixnum>0</Fixnum> </lit> </array> <call startline="9"> <Nil /> <Symbol>p</Symbol> <arglist startline="9"> <str startline="8"> <String>test</String> </str> </arglist> </call> </when> <Nil /> </case> <until startline="11"> <call startline="11"> <lvar startline="11"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="11"> <lit startline="11"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block> <call startline="11"> <Nil /> <Symbol>p</Symbol> <arglist startline="11"> <str startline="11"> <String>test</String> </str> </arglist> </call> </block> <TrueClass>true</TrueClass> </until> <until startline="12"> <call startline="12"> <lvar startline="12"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="12"> <lit startline="12"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block> <call startline="12"> <Nil /> <Symbol>p</Symbol> <arglist startline="12"> <str startline="12"> <String>test</String> </str> </arglist> </call> </block> <TrueClass>true</TrueClass> </until> <for startline="13"> <array startline="13" /> <lasgn startline="13"> <Symbol>y</Symbol> </lasgn> <block> <call startline="13"> <Nil /> <Symbol>p</Symbol> <arglist startline="13"> <str startline="13"> <String>test</String> </str> </arglist> </call> </block> </for> <iter startline="14"> <call startline="14"> <Nil /> <Symbol>loop</Symbol> <arglist startline="14" /> </call> <Nil /> <block> <call startline="14"> <Nil /> <Symbol>p</Symbol> <arglist startline="14"> <str startline="14"> <String>test</String> </str> </arglist> </call> </block> </iter> <iter startline="15"> <call startline="15"> <Nil /> <Symbol>loop</Symbol> <arglist startline="15" /> </call> <Nil /> <block> <call startline="15"> <Nil /> <Symbol>p</Symbol> <arglist startline="15"> <str startline="15"> <String>test</String> </str> </arglist> </call> </block> </iter> <iter startline="16"> <call startline="16"> <array startline="16" /> <Symbol>each</Symbol> <arglist startline="16" /> </call> <lasgn startline="16"> <Symbol>b</Symbol> </lasgn> <block> <call startline="16"> <Nil /> <Symbol>p</Symbol> <arglist startline="16"> <str startline="16"> <String>test</String> </str> </arglist> </call> </block> </iter> <iter startline="17"> <call startline="17"> <array startline="17" /> <Symbol>each</Symbol> <arglist startline="17" /> </call> <lasgn startline="17"> <Symbol>b</Symbol> </lasgn> <block> <call startline="17"> <Nil /> <Symbol>p</Symbol> <arglist startline="17"> <str startline="17"> <String>test</String> </str> </arglist> </call> </block> </iter> <iter startline="18"> <call startline="18"> <Nil /> <Symbol>lambda</Symbol> <arglist startline="18" /> </call> <lasgn startline="18"> <Symbol>x</Symbol> </lasgn> <block> <call startline="18"> <Nil /> <Symbol>p</Symbol> <arglist startline="18"> <str startline="18"> <String>test</String> </str> </arglist> </call> </block> </iter> <iter startline="19"> <call startline="19"> <Nil /> <Symbol>lambda</Symbol> <arglist startline="19" /> </call> <lasgn startline="19"> <Symbol>x</Symbol> </lasgn> <block> <call startline="19"> <Nil /> <Symbol>p</Symbol> <arglist startline="19"> <str startline="19"> <String>test</String> </str> </arglist> </call> </block> </iter> <lasgn startline="21"> <Symbol>i</Symbol> <lit startline="21"> <Fixnum>0</Fixnum> </lit> </lasgn> <if startline="23"> <call startline="23"> <lvar startline="23"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="23"> <lit startline="23"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block> <call startline="25"> <Nil /> <Symbol>p</Symbol> <arglist startline="25"> <str startline="24"> <String>test</String> </str> </arglist> </call> </block> <block /> </if> <if startline="27"> <call startline="27"> <lvar startline="27"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="27"> <lit startline="27"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block> <call startline="29"> <Nil /> <Symbol>p</Symbol> <arglist startline="29"> <str startline="28"> <String>test</String> </str> </arglist> </call> </block> <block /> </if> <case startline="32"> <lvar startline="32"> <Symbol>i</Symbol> </lvar> <when startline="32"> <array startline="33"> <lit startline="32"> <Fixnum>0</Fixnum> </lit> </array> <call startline="34"> <Nil /> <Symbol>p</Symbol> <arglist startline="34"> <str startline="33"> <String>test</String> </str> </arglist> </call> </when> <Nil /> </case> <until startline="36"> <call startline="36"> <lvar startline="36"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="36"> <lit startline="36"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block> <call startline="38"> <Nil /> <Symbol>p</Symbol> <arglist startline="38"> <str startline="37"> <String>test</String> </str> </arglist> </call> </block> <TrueClass>true</TrueClass> </until> <until startline="40"> <call startline="40"> <lvar startline="40"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="40"> <lit startline="40"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block> <call startline="42"> <Nil /> <Symbol>p</Symbol> <arglist startline="42"> <str startline="41"> <String>test</String> </str> </arglist> </call> </block> <TrueClass>true</TrueClass> </until> <for startline="44"> <array startline="44" /> <lasgn startline="44"> <Symbol>y</Symbol> </lasgn> <block> <call startline="46"> <Nil /> <Symbol>p</Symbol> <arglist startline="46"> <str startline="45"> <String>test</String> </str> </arglist> </call> </block> </for> <iter startline="48"> <call startline="50"> <Nil /> <Symbol>loop</Symbol> <arglist startline="50" /> </call> <Nil /> <block> <call startline="50"> <Nil /> <Symbol>p</Symbol> <arglist startline="50"> <str startline="49"> <String>test</String> </str> </arglist> </call> </block> </iter> <iter startline="52"> <call startline="54"> <Nil /> <Symbol>loop</Symbol> <arglist startline="54" /> </call> <Nil /> <block> <call startline="54"> <Nil /> <Symbol>p</Symbol> <arglist startline="54"> <str startline="53"> <String>test</String> </str> </arglist> </call> </block> </iter> <iter startline="56"> <call startline="56"> <array startline="56" /> <Symbol>each</Symbol> <arglist startline="56" /> </call> <lasgn startline="56"> <Symbol>b</Symbol> </lasgn> <block> <call startline="58"> <Nil /> <Symbol>p</Symbol> <arglist startline="58"> <str startline="57"> <String>test</String> </str> </arglist> </call> </block> </iter> <iter startline="60"> <call startline="60"> <array startline="60" /> <Symbol>each</Symbol> <arglist startline="60" /> </call> <lasgn startline="60"> <Symbol>b</Symbol> </lasgn> <block> <call startline="62"> <Nil /> <Symbol>p</Symbol> <arglist startline="62"> <str startline="61"> <String>test</String> </str> </arglist> </call> </block> </iter> <iter startline="64"> <call startline="66"> <Nil /> <Symbol>lambda</Symbol> <arglist startline="66" /> </call> <lasgn startline="64"> <Symbol>x</Symbol> </lasgn> <block> <call startline="66"> <Nil /> <Symbol>p</Symbol> <arglist startline="66"> <str startline="65"> <String>test</String> </str> </arglist> </call> </block> </iter> <iter startline="68"> <call startline="70"> <Nil /> <Symbol>lambda</Symbol> <arglist startline="70" /> </call> <lasgn startline="68"> <Symbol>x</Symbol> </lasgn> <block> <call startline="70"> <Nil /> <Symbol>p</Symbol> <arglist startline="70"> <str startline="69"> <String>test</String> </str> </arglist> </call> </block> </iter> </block>
exKAZUu/ParserTests
fixture/Ruby19/input_code/ruby2ruby_test.rb
i = 0 if (i == 0) then p(i) else end
exKAZUu/ParserTests
fixture/Ruby19/input_code/prime.rb
def prime_table(max) result = Array.new(max + 1, true) result[0] = result[1] = false (2..Math::sqrt(max).ceil).each { |i| next unless result[i] (i*2).step(max, i) { |j| result[j] = false } } result end def prime_list(table) result = [] table.each_with_index { |b, i| result << i if b } result end def prime_check_table(min, max, primes) result = Array.new(max - min + 1, true) result[0] = false if min == 1 maxsq = Math::sqrt(max).ceil i = 1 while (p = primes[i]) <= maxsq (min + p - 1 - (min + p - 1) % p).step(max, p) { |j| result[j - min] = false } i += 1 end return result end def show_primes(min, offset, max, table) while min <= max puts min + offset if table[min] min += 2 end end if __FILE__ == $0 max_prime = 50000 table = prime_table(max_prime) primes = prime_list(table) primes << 1000000000 # sentry gets.chomp.to_i.times { |i| puts unless i == 0 min, max = gets.split.map { |s| s.to_i } puts 2 if min <= 2 min += 1 if min & 1 == 0 max -= 1 if max & 1 == 0 if max <= max_prime show_primes(min, 0, max, table) else if min <= max_prime show_primes(min, 0, max_prime, table) min = max_prime + 1 min += 1 if min & 1 == 0 end result = prime_check_table(min, max, primes) show_primes(0, min, max - min, result) end } end x = 1 case x when 1 p "1" when 2 p "2" else p "else" end x == 1 ? "a" : "b" while x >= 0 do p "a"; p "a"; end while x >= 0 do p "a" end until x < 0 do p "a" end for y in [] do p 'c' end def a() p 'c' end [].each { |b| p b } [].each do |b| p b end
exKAZUu/ParserTests
fixture/Ruby19/expected_xml/Block4.rb
<block startline="1"> <lasgn startline="1"> <Symbol>i</Symbol> <lit startline="1"> <Fixnum>0</Fixnum> </lit> </lasgn> <if startline="3"> <call startline="3"> <lvar startline="3"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <lit startline="3"> <Fixnum>0</Fixnum> </lit> </call> <nil /> <nil /> </if> <if startline="4"> <call startline="4"> <lvar startline="4"> <Symbol>i</Symbol> </lvar> <Symbol>!=</Symbol> <lit startline="4"> <Fixnum>0</Fixnum> </lit> </call> <nil /> <nil /> </if> <case startline="6"> <lvar startline="6"> <Symbol>i</Symbol> </lvar> <when startline="7"> <array startline="8"> <lit startline="7"> <Fixnum>0</Fixnum> </lit> </array> <call startline="8"> <nil /> <Symbol>p</Symbol> <str startline="8"> <String>test</String> </str> </call> </when> <nil /> </case> <while startline="11"> <call startline="11"> <lvar startline="11"> <Symbol>i</Symbol> </lvar> <Symbol>!=</Symbol> <lit startline="11"> <Fixnum>0</Fixnum> </lit> </call> <call startline="11"> <nil /> <Symbol>p</Symbol> <str startline="11"> <String>test</String> </str> </call> <TrueClass>true</TrueClass> </while> <until startline="12"> <call startline="12"> <lvar startline="12"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <lit startline="12"> <Fixnum>0</Fixnum> </lit> </call> <call startline="12"> <nil /> <Symbol>p</Symbol> <str startline="12"> <String>test</String> </str> </call> <TrueClass>true</TrueClass> </until> <for startline="13"> <array startline="13"></array> <lasgn startline="13"> <Symbol>y</Symbol> </lasgn> <call startline="13"> <nil /> <Symbol>p</Symbol> <str startline="13"> <String>test</String> </str> </call> </for> <iter startline="14"> <call startline="14"> <nil /> <Symbol>loop</Symbol> </call> <args startline="14"></args> <call startline="14"> <nil /> <Symbol>p</Symbol> <str startline="14"> <String>test</String> </str> </call> </iter> <iter startline="15"> <call startline="15"> <nil /> <Symbol>loop</Symbol> </call> <args startline="15"></args> <call startline="15"> <nil /> <Symbol>p</Symbol> <str startline="15"> <String>test</String> </str> </call> </iter> <iter startline="16"> <call startline="16"> <array startline="16"></array> <Symbol>each</Symbol> </call> <args startline="16"> <Symbol>b</Symbol> </args> <call startline="16"> <nil /> <Symbol>p</Symbol> <str startline="16"> <String>test</String> </str> </call> </iter> <iter startline="17"> <call startline="17"> <array startline="17"></array> <Symbol>each</Symbol> </call> <args startline="17"> <Symbol>b</Symbol> </args> <call startline="17"> <nil /> <Symbol>p</Symbol> <str startline="17"> <String>test</String> </str> </call> </iter> <iter startline="18"> <call startline="18"> <nil /> <Symbol>lambda</Symbol> </call> <args startline="18"> <Symbol>x</Symbol> </args> <call startline="18"> <nil /> <Symbol>p</Symbol> <str startline="18"> <String>test</String> </str> </call> </iter> <iter startline="19"> <call startline="19"> <nil /> <Symbol>lambda</Symbol> </call> <args startline="19"> <Symbol>x</Symbol> </args> <call startline="19"> <nil /> <Symbol>p</Symbol> <str startline="19"> <String>test</String> </str> </call> </iter> <lasgn startline="21"> <Symbol>i</Symbol> <lit startline="21"> <Fixnum>0</Fixnum> </lit> </lasgn> <if startline="23"> <call startline="23"> <lvar startline="23"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <lit startline="23"> <Fixnum>0</Fixnum> </lit> </call> <call startline="24"> <nil /> <Symbol>p</Symbol> <str startline="24"> <String>test</String> </str> </call> <nil /> </if> <if startline="27"> <call startline="27"> <lvar startline="27"> <Symbol>i</Symbol> </lvar> <Symbol>!=</Symbol> <lit startline="27"> <Fixnum>0</Fixnum> </lit> </call> <nil /> <call startline="28"> <nil /> <Symbol>p</Symbol> <str startline="28"> <String>test</String> </str> </call> </if> <case startline="31"> <lvar startline="31"> <Symbol>i</Symbol> </lvar> <when startline="32"> <array startline="33"> <lit startline="32"> <Fixnum>0</Fixnum> </lit> </array> <call startline="33"> <nil /> <Symbol>p</Symbol> <str startline="33"> <String>test</String> </str> </call> </when> <nil /> </case> <while startline="36"> <call startline="36"> <lvar startline="36"> <Symbol>i</Symbol> </lvar> <Symbol>!=</Symbol> <lit startline="36"> <Fixnum>0</Fixnum> </lit> </call> <call startline="37"> <nil /> <Symbol>p</Symbol> <str startline="37"> <String>test</String> </str> </call> <TrueClass>true</TrueClass> </while> <until startline="40"> <call startline="40"> <lvar startline="40"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <lit startline="40"> <Fixnum>0</Fixnum> </lit> </call> <call startline="41"> <nil /> <Symbol>p</Symbol> <str startline="41"> <String>test</String> </str> </call> <TrueClass>true</TrueClass> </until> <for startline="44"> <array startline="44"></array> <lasgn startline="44"> <Symbol>y</Symbol> </lasgn> <call startline="45"> <nil /> <Symbol>p</Symbol> <str startline="45"> <String>test</String> </str> </call> </for> <iter startline="48"> <call startline="48"> <nil /> <Symbol>loop</Symbol> </call> <args startline="50"></args> <call startline="49"> <nil /> <Symbol>p</Symbol> <str startline="49"> <String>test</String> </str> </call> </iter> <iter startline="52"> <call startline="52"> <nil /> <Symbol>loop</Symbol> </call> <args startline="54"></args> <call startline="53"> <nil /> <Symbol>p</Symbol> <str startline="53"> <String>test</String> </str> </call> </iter> <iter startline="56"> <call startline="56"> <array startline="56"></array> <Symbol>each</Symbol> </call> <args startline="56"> <Symbol>b</Symbol> </args> <call startline="57"> <nil /> <Symbol>p</Symbol> <str startline="57"> <String>test</String> </str> </call> </iter> <iter startline="60"> <call startline="60"> <array startline="60"></array> <Symbol>each</Symbol> </call> <args startline="60"> <Symbol>b</Symbol> </args> <call startline="61"> <nil /> <Symbol>p</Symbol> <str startline="61"> <String>test</String> </str> </call> </iter> <iter startline="64"> <call startline="64"> <nil /> <Symbol>lambda</Symbol> </call> <args startline="64"> <Symbol>x</Symbol> </args> <call startline="65"> <nil /> <Symbol>p</Symbol> <str startline="65"> <String>test</String> </str> </call> </iter> <iter startline="68"> <call startline="68"> <nil /> <Symbol>lambda</Symbol> </call> <args startline="68"> <Symbol>x</Symbol> </args> <call startline="69"> <nil /> <Symbol>p</Symbol> <str startline="69"> <String>test</String> </str> </call> </iter> </block>
exKAZUu/ParserTests
fixture/Ruby19/expected_xml/student.rb
<filename>fixture/Ruby19/expected_xml/student.rb <block startline="1"> <class startline="1"> <Symbol>Student</Symbol> <nil /> <defn startline="2"> <Symbol>initialize</Symbol> <args startline="2"> <Symbol>name</Symbol> </args> <iasgn startline="3"> <Symbol>@name</Symbol> <lvar startline="3"> <Symbol>name</Symbol> </lvar> </iasgn> </defn> <defn startline="6"> <Symbol>name</Symbol> <args startline="6"></args> <ivar startline="7"> <Symbol>@name</Symbol> </ivar> </defn> </class> <lasgn startline="11"> <Symbol>students</Symbol> <call startline="11"> <const startline="11"> <Symbol>Array</Symbol> </const> <Symbol>new</Symbol> <lit startline="11"> <Fixnum>2</Fixnum> </lit> </call> </lasgn> <attrasgn startline="12"> <lvar startline="12"> <Symbol>students</Symbol> </lvar> <Symbol>[]=</Symbol> <lit startline="12"> <Fixnum>0</Fixnum> </lit> <call startline="12"> <const startline="12"> <Symbol>Student</Symbol> </const> <Symbol>new</Symbol> <str startline="12"> <String>Tom</String> </str> </call> </attrasgn> <attrasgn startline="13"> <lvar startline="13"> <Symbol>students</Symbol> </lvar> <Symbol>[]=</Symbol> <lit startline="13"> <Fixnum>1</Fixnum> </lit> <call startline="13"> <const startline="13"> <Symbol>Student</Symbol> </const> <Symbol>new</Symbol> <str startline="13"> <String>Anna</String> </str> </call> </attrasgn> <for startline="15"> <lvar startline="15"> <Symbol>students</Symbol> </lvar> <lasgn startline="15"> <Symbol>student</Symbol> </lasgn> <call startline="16"> <nil /> <Symbol>puts</Symbol> <call startline="16"> <lvar startline="16"> <Symbol>student</Symbol> </lvar> <Symbol>name</Symbol> </call> </call> </for> </block>
Alamex/mailboxer
lib/mailboxer/version.rb
module Mailboxer VERSION = "0.12.4" end
esjeon/graveyard
eml2mbox.rb
#!/usr/bin/ruby #============================================================================================# # eml2mbox.rb v0.08 # # Last updated: Jan 23, 2004 # # # # Converts a bunch of eml files into one mbox file. # # # # Usage: [ruby] eml2mbx.rb [-c] [-l] [-s] [-yz] [emlpath [trgtmbx]] # # Switches: # # -c Remove CRs (^M) appearing at end of lines (Unix) # # -l Remove LFs appearing at beggining of lines (old Mac) - not tested # # -s Don't use standard mbox postmark formatting (for From_ line) # # This will force the use of original From and Date found in mail headers. # # Not recommended, unless you really have problems importing emls. # # -yz Use this to force the order of the year and timezone in date in the From_ # # line from the default [timezone][year] to [year][timezone]. # # emlpath - Path of dir with eml files. Defaults to the current dir if not specified # # trgtmbx - Name of the target mbox file. Defaults to "archive.mbox" in 'emlpath' # # # # Ruby homepage: http://www.ruby-lang.org/en/ # # Unix mailbox format: http://www.broobles.com/eml2mbox/mbox.html # # This script : http://www.broobles.com/eml2mbox # # # #============================================================================================# # Licence: # # # # This script is free software; you can redistribute it and/or modify it under the terms of # # the GNU Lesser General Public License as published by the Free Software Foundation; # # either version 2.1 of the License, or (at your option) any later version. # # # # You should have received a copy of the GNU Lesser General Public License along with this # # script; if not, please visit http://www.gnu.org/copyleft/gpl.html for more information. # #============================================================================================# require 'date/format' require 'time' #=======================================================# # Class that encapsulates the processing file in memory # #=======================================================# class FileInMemory ZoneOffset = { # Standard zones by RFC 2822 'UTC' => '0000', 'UT' => '0000', 'GMT' => '0000', 'EST' => '-0500', 'EDT' => '-0400', 'CST' => '-0600', 'CDT' => '-0500', 'MST' => '-0700', 'MDT' => '-0600', 'PST' => '-0800', 'PDT' => '-0700', } def initialize() @lines = Array.new @counter = 1 # keep the 0 position for the From_ line @from = nil # from part of the From_ line @date = nil # date part of the From_ line end def addLine(line) # If the line is a 'false' From line, add a '>' to its beggining line = line.sub(/From/, '>From') if line =~ /^From/ and @from!=nil # If the line is the first valid From line, save it (without the line break) if line =~ /^From:\s.*@/ and @from==nil @from = line.sub(/From:/,'From') @from = @from.chop # Remove line break(s) @from = standardizeFrom(@from) unless $switches["noStandardFromLine"] end # Get the date if $switches["noStandardFromLine"] # Don't parse the content of the Date header @date = line.sub(/Date:\s/,'') if line =~ /^Date:\s/ and @date==nil else if line =~ /^Date:\s/ and @date==nil # Parse content of the Date header and convert to the mbox standard for the From_ line @date = line.sub(/Date:\s/,'') year, month, day, hour, minute, second, timezone, wday = Date._parse(@date).values_at(:year, :mon, :mday, :hour, :min, :sec, :zone, :wday) # Need to convert the timezone from a string to a 4 digit offset unless timezone =~ /[+|-]\d*/ timezone=ZoneOffset[timezone] end time = Time.gm(year,month,day,hour,minute,second) @date = formMboxDate(time,timezone) end end # Now add the line to the array line = fixLineEndings(line) @lines[@counter]=line @counter+=1 end # Forms the first line (from + date) and returns all the lines # Returns all the lines in the file def getProcessedLines() if @from != nil # Add from and date to the first line if @date==nil puts "WARN: Failed to extract date. Will use current time in the From_ line" @date=formMboxDate(Time.now,nil) end @lines[0] = @from + " " + @date @lines[0] = fixLineEndings(@lines[0]) @lines[@counter] = "" return @lines end # else don't return anything end # Fixes CR/LFs def fixLineEndings(line) line = removeCR(line) if $switches["removeCRs"]; line = removeLF(line) if $switches["removeLFs"]; return line end # emls usually have CR+LF (DOS) line endings, Unix uses LF as a line break, # so there's a hanging CR at the end of the line when viewed on Unix. # This method will remove the next to the last character from a line def removeCR(line) line = line[0..-3]+line[-1..-1] if line[-2]==0xD return line end # Similar to the above. This one is for Macs that use CR as a line break. # So, remove the last char def removeLF(line) line = line[0..-2] if line[-1]==0xA return line end end #================# # Helper methods # #================# # Converts: 'From "some one <<EMAIL>>" <<EMAIL>>' -> 'From <EMAIL>' def standardizeFrom(fromLine) # Get indexes of last "<" and ">" in line openIndex = fromLine.rindex('<') closeIndex = fromLine.rindex('>') if openIndex!=nil and closeIndex!=nil fromLine = fromLine[0..4]+fromLine[openIndex+1..closeIndex-1] end # else leave as it is - it is either already well formed or is invalid return fromLine end # Returns a mbox postmark formatted date. # If timezone is unknown, it is skipped. # mbox date format used is described here: # http://www.broobles.com/eml2mbox/mbox.html def formMboxDate(time,timezone) if timezone==nil return time.strftime("%a %b %d %H:%M:%S %Y") else if $switches["zoneYearOrder"] return time.strftime("%a %b %d %H:%M:%S "+timezone.to_s+" %Y") else return time.strftime("%a %b %d %H:%M:%S %Y "+timezone.to_s) end end end # Extracts all switches from the command line and returns # a hashmap with valid switch names as keys and booleans as values # Moves real params to the beggining of the ARGV array def extractSwitches() switches = Hash.new(false) # All switches (values) default to false i=0 while (ARGV[i]=~ /^-/) # while arguments are switches if ARGV[i]=="-c" switches["removeCRs"] = true puts "\nWill fix lines ending with a CR" elsif ARGV[i]=="-l" switches["removeLFs"] = true puts "\nWill fix lines beggining with a LF" elsif ARGV[i]=="-s" switches["noStandardFromLine"] = true puts "\nWill use From and Date from mail headers in From_ line" elsif ARGV[i]=="-yz" switches["zoneYearOrder"] = true puts "\nTimezone will be placed before the year in From_ line" else puts "\nUnknown switch: "+ARGV[i]+". Ignoring." end i = i+1 end # Move real arguments to the beggining of the array ARGV[0] = ARGV[i] ARGV[1] = ARGV[i+1] return switches end #===============# # Main # #===============# $switches = extractSwitches() # Extract specified directory with emls and the target archive (if any) emlDir = "." # default if not specified emlDir = ARGV[0] if ARGV[0]!=nil mboxArchive = emlDir+"/archive.mbox" # default if not specified mboxArchive = ARGV[1] if ARGV[1] != nil # Show specified settings puts "\nSpecified dir : "+emlDir puts "Specified file: "+mboxArchive+"\n" # Check that the dir exists if FileTest.directory?(emlDir) Dir.chdir(emlDir) else puts "\n["+emlDir+"] is not a directory (might not exist). Please specify a valid dir" exit(0) end # Check if destination file exists. If yes allow user to select an option. canceled = false if FileTest.exist?(mboxArchive) print "\nFile ["+mboxArchive+"] exists! Please select: [A]ppend [O]verwrite [C]ancel (default) " sel = STDIN.gets.chomp if sel == 'A' or sel == 'a' aFile = File.new(mboxArchive, "a"); elsif sel == 'O' or sel == 'o' aFile = File.new(mboxArchive, "w"); else canceled = true end else # File doesn't exist, open for writing aFile = File.new(mboxArchive, "w"); end if not canceled puts files = Dir["*.eml"] if files.size == 0 puts "No *.eml files in this directory. mbox file not created." aFile.close File.delete(mboxArchive) exit(0) end # For each .eml file in the specified directory do the following files.each() do |x| puts "Processing file: "+x thisFile = FileInMemory.new() File.open(x).each {|item| thisFile.addLine(item) } lines = thisFile.getProcessedLines if lines == nil puts "WARN: File ["+x+"] doesn't seem to have a regular From: line. Not included in mbox" else lines.each {|line| aFile.puts line} end end aFile.close end
JumpMaster/PiSofa
API/PiSofa.rb
gem 'pi_piper', '= 1.3.2' #gem 'pi_piper', '= 2.0.beta.4' require 'pi_piper' require './PiSeat' class PiSofa include PiPiper def initialize puts Gem.loaded_specs["pi_piper"].version.version @up, @down = 1, 2 @crazyMode = false @switchRelay = PiPiper::Pin.new(:pin => 27, :direction => :out) @switchRelay.on @@seat = [] @@seat << PiSeat.new(1,7,11,5300,8300) @@seat << PiSeat.new(2,22,8,4900,8000) @@seat << PiSeat.new(3,9,10,4900,8000) sofa0pinUp, sofa0pinDown = 17,4 sofa1pinUp, sofa1pinDown = 3,2 sofa2pinUp, sofa2pinDown = 18,23 @@seatPin = [[0,1],[0,2],[1,1],[1,2],[2,1],[2,2]] after :pin => sofa0pinUp, :goes => :high do @@seat[@@seatPin[0][0]].buttonReleased(@@seatPin[0][1]) end after :pin => sofa0pinUp, :goes => :low do @@seat[@@seatPin[0][0]].buttonPressed(@@seatPin[0][1]) end after :pin => sofa0pinDown, :goes => :high do @@seat[@@seatPin[1][0]].buttonReleased(@@seatPin[1][1]) end after :pin => sofa0pinDown, :goes => :low do @@seat[@@seatPin[1][0]].buttonPressed(@@seatPin[1][1]) end after :pin => sofa1pinUp, :goes => :high do @@seat[@@seatPin[2][0]].buttonReleased(@@seatPin[2][1]) end after :pin => sofa1pinUp, :goes => :low do @@seat[@@seatPin[2][0]].buttonPressed(@@seatPin[2][1]) end after :pin => sofa1pinDown, :goes => :high do @@seat[@@seatPin[3][0]].buttonReleased(@@seatPin[3][1]) end after :pin => sofa1pinDown, :goes => :low do @@seat[@@seatPin[3][0]].buttonPressed(@@seatPin[3][1]) end after :pin => sofa2pinUp, :goes => :high do @@seat[@@seatPin[4][0]].buttonReleased(@@seatPin[4][1]) end after :pin => sofa2pinUp, :goes => :low do @@seat[@@seatPin[4][0]].buttonPressed(@@seatPin[4][1]) end after :pin => sofa2pinDown, :goes => :high do @@seat[@@seatPin[5][0]].buttonReleased(@@seatPin[5][1]) end after :pin => sofa2pinDown, :goes => :low do @@seat[@@seatPin[5][0]].buttonPressed(@@seatPin[5][1]) end end def up @up end def down @down end def toggleParentalMode @switchRelay.read if (@switchRelay.off?) @switchRelay.on else @switchRelay.off end end def isParentalMode @switchRelay.read return @switchRelay.off?.to_s end def stopAll @@seat.each do |seat| if seat.isMoving() seat.stopMoving() end end end def getPositions returnValue = "" @@seat.each_with_index do |seat, i| position = seat.getPosition() returnValue += "Sofa#{i+1} = #{position}\n" end returnValue end def moveToUp(id) if id == 0 @@seat.each do |seat| seat.moveToUp() end else @@seat[id-1].moveToUp() end end def moveToFeet(id) if id == 0 @@seat.each do |seat| seat.moveToFeet() end else @@seat[id-1].moveToFeet() end end def moveToFlat(id) if id == 0 @@seat.each do |seat| seat.moveToFlat() end else @@seat[id-1].moveToFlat() end end def startManualMove(id, direction) if id == 0 @@seat.each do |seat| seat.startMoving(direction) end else @@seat[id-1].startMoving(direction) end end def stopManualMove(id) if id == 0 @@seat.each do |seat| seat.stopMoving() end else @@seat[id-1].stopMoving() end end def toggleCrazyMode @crazyMode = !@crazyMode if @crazyMode @@seatPin = @@seatPin.shuffle @@seatPin = @@seatPin.shuffle else @@seatPin = @@seatPin.sort end end def isCrazyMode @crazyMode end end
JumpMaster/PiSofa
API/PiSeat.rb
<reponame>JumpMaster/PiSofa gem 'pi_piper', '= 1.3.2' #gem 'pi_piper', '= 2.0.beta.4' require 'pi_piper' class PiSeat def initialize(seat, pinDownRelay, pinUpRelay, feetUpTime, flatTime) self.setRelays(pinUpRelay, pinDownRelay) self.setTimings(feetUpTime, flatTime) @seat = seat @dClickTime = 500 @clickTime = 200 @bounceTime = 150 @moveBuffer = 500 @dClicked = false @bounced = false @moving = 0 @moveTarget = 0 @pressTime = 0 @moveStartTime = 0 @moveTarget = 0 @up = 1 @down = 2 @seatPos = 0 end def getPosition getCurrentPos() end def isMoving @moving != 0 end def setTimings(feetUpTime, flatTime) @posFeetUp = feetUpTime @posFlat = flatTime end def setRelays(pinUpRelay, pinDownRelay) @upRelayPin = pinUpRelay @downRelayPin = pinDownRelay @upRelay = PiPiper::Pin.new(:pin => pinUpRelay, :direction => :out) @downRelay = PiPiper::Pin.new(:pin => pinDownRelay, :direction => :out) end def buttonPressed(direction) time = (Time.now.to_f*1000).to_i if (direction == @up) puts Time.now.strftime("%d/%m/%y %H:%M:%S:%L - S#{@seat} - #{@upRelayPin} pressed") else puts Time.now.strftime("%d/%m/%y %H:%M:%S:%L - S#{@seat} - #{@downRelayPin} pressed") end if time-@pressTime < @bounceTime puts Time.now.strftime("%d/%m/%y %H:%M:%S:%L - S#{@seat} - Bounce detected") @bounced = true return end if @moving == direction && !@dClicked && time-@pressTime < @dClickTime puts Time.now.strftime("%d/%m/%y %H:%M:%S:%L - S#{@seat} - Double Clicked") if @moving > 0 direction == @up ? @moveTarget = 0 : @moveTarget = @posFlat moveToTarget() @dClicked = true end else @pressTime = time @dClicked = false if @moving != 0 if defined?(@moveThread) Thread.kill(@moveThread) end stopMoving() else startMoving(direction) end end end def buttonReleased(direction) time = (Time.now.to_f*1000).to_i if (direction == @up) puts Time.now.strftime("%d/%m/%y %H:%M:%S:%L - S#{@seat} - #{@upRelayPin} released") else puts Time.now.strftime("%d/%m/%y %H:%M:%S:%L - S#{@seat} - #{@downRelayPin} released") end if @moving == 0 || @bounced || @dClicked @bounced = false return end if (time-@pressTime <= @clickTime) && (direction == @down && getCurrentPos() < @posFlat || direction == @up && getCurrentPos() > 0) puts Time.now.strftime("%d/%m/%y %H:%M:%S:%L - S#{@seat} - Quick Click") currentPos = getCurrentPos() if direction == @up @moveTarget = currentPos > @posFeetUp ? @posFeetUp : 0 else @moveTarget = currentPos < @posFeetUp ? @posFeetUp : @posFlat end moveToTarget() else puts Time.now.strftime("%d/%m/%y %H:%M:%S:%L - S#{@seat} - Slow Click") stopMoving() end end def startMoving(direction) if direction == @up @downRelay.on elsif direction == @down @upRelay.on end @moving = direction @moveStartTime = (Time.now.to_f*1000).to_i end def stopMoving() time = (Time.now.to_f*1000).to_i if @moving == @up @downRelay.off @seatPos -= (time-@moveStartTime) elsif @moving == @down @upRelay.off @seatPos += (time-@moveStartTime) end if @seatPos < 0 @seatPos = 0 elsif @seatPos > @posFlat @seatPos = @posFlat end @moving = 0 @moveStartTime = 0 puts Time.now.strftime("%d/%m/%y %H:%M:%S:%L - S#{@seat} - Stopped @ #{@seatPos}") end def getCurrentPos() time = (Time.now.to_f*1000).to_i case @moving when 0 currentPos = @seatPos when @up currentPos = @seatPos - (time-@moveStartTime) when @down currentPos = @seatPos + (time-@moveStartTime) end if currentPos > @posFlat return @posFlat elsif currentPos < 0 return 0 else return currentPos end end def moveToTarget currentPos = getCurrentPos() if @moveTarget > currentPos if @moving == @up stopMoving() startMoving(@down) elsif !isMoving() startMoving(@down) end sleepTime = @moveTarget-currentPos if @moveTarget == @posFlat sleepTime += @moveBuffer end moveSleepThread(sleepTime.to_f/1000) elsif @moveTarget < currentPos if @moving == @down stopMoving() startMoving(@up) elsif !isMoving() startMoving(@up) end sleepTime = currentPos-@moveTarget if @moveTarget == 0 sleepTime += @moveBuffer end moveSleepThread(sleepTime.to_f/1000) end end def moveSleepThread(sleepTime) if defined?(@moveThread) Thread.kill(@moveThread) end @moveThread = Thread.new do sleep(sleepTime) stopMoving() @seatPos = @moveTarget end end def moveToUp @moveTarget = 0 moveToTarget() end def moveToFeet @moveTarget = @posFeetUp moveToTarget() end def moveToFlat @moveTarget = @posFlat moveToTarget() end end
JumpMaster/PiSofa
API/Site.rb
require 'sinatra' require './PiSofa' class PiSofaSite < Sinatra::Base configure do @@piSofa = PiSofa.new end before do expires 0, :public, :must_revalidate, :'no-cache' end get '/' do erb :index end get '/moveToUp/:id' do id = params[:id].to_i @@piSofa.moveToUp(id) status 200 end get '/moveToFeet/:id' do id = params[:id].to_i @@piSofa.moveToFeet(id) status 200 end get '/moveToFlat/:id' do id = params[:id].to_i @@piSofa.moveToFlat(id) status 200 end get '/stopAll' do @@piSofa.stopAll status 200 end get '/parentalMode' do @@piSofa.toggleParentalMode erb @@piSofa.isParentalMode.to_s end get '/isParentalMode' do erb @@piSofa.isParentalMode.to_s end get '/crazyMode' do @@piSofa.toggleCrazyMode erb @@piSofa.isCrazyMode.to_s end get '/isCrazyMode' do erb @@piSofa.isCrazyMode.to_s end get '/showData' do erb @@piSofa.getPositions end get '/showData2' do erb :showData2 end get '/manUpPress/:id' do id = params[:id].to_i @@piSofa.startManualMove(id, @@piSofa.up) status 200 end get '/manDownPress/:id' do id = params[:id].to_i @@piSofa.startManualMove(id, @@piSofa.down) status 200 end get '/manUpRelease/:id' do id = params[:id].to_i @@piSofa.stopManualMove(id) status 200 end get '/manDownRelease/:id' do id = params[:id].to_i @@piSofa.stopManualMove(id) status 200 end end
JumpMaster/PiSofa
API/config.ru
require './Site.rb' run PiSofaSite
cosmo0920/fluent-plugin-docker_metadata_filter
test/plugin/test_filter_docker_metadata.rb
<gh_stars>1-10 # # Fluentd Docker Metadata Filter Plugin - Enrich Fluentd events with Docker # metadata # # Copyright 2015 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require_relative '../helper' require 'fluent/plugin/filter_docker_metadata' require 'webmock/test_unit' WebMock.disable_net_connect! class DockerMetadataFilterTest < Test::Unit::TestCase include Fluent setup do Fluent::Test.setup @time = Fluent::Engine.now end def create_driver(conf = '') Test::FilterTestDriver.new(DockerMetadataFilter).configure(conf, true) end sub_test_case 'configure' do test 'check default' do d = create_driver assert_equal(d.instance.docker_url, 'unix:///var/run/docker.sock') assert_equal(100, d.instance.cache_size) end test 'docker url' do d = create_driver(%[docker_url http://docker-url]) assert_equal('http://docker-url', d.instance.docker_url) assert_equal(100, d.instance.cache_size) end test 'cache size' do d = create_driver(%[cache_size 1]) assert_equal('unix:///var/run/docker.sock', d.instance.docker_url) assert_equal(1, d.instance.cache_size) end end sub_test_case 'filter_stream' do def messages [ "2013/01/13T07:02:11.124202 INFO GET /ping", "2013/01/13T07:02:13.232645 WARN POST /auth", "2013/01/13T07:02:21.542145 WARN GET /favicon.ico", "2013/01/13T07:02:43.632145 WARN POST /login", ] end def emit(config, msgs, tag='df14e0d5ae4c07284fa636d739c8fc2e6b52bc344658de7d3f08c36a2e804115') d = create_driver(config) d.run { msgs.each { |msg| d.emit_with_tag(tag, {'foo' => 'bar', 'message' => msg}, @time) } }.filtered end test 'docker metadata' do VCR.use_cassette('docker_metadata') do es = emit('', messages) assert_equal(4, es.instance_variable_get(:@record_array).size) assert_equal('df14e0d5ae4c07284fa636d739c8fc2e6b52bc344658de7d3f08c36a2e804115', es.instance_variable_get(:@record_array)[0]['docker']['id']) assert_equal('k8s_fabric8-console-container.efbd6e64_fabric8-console-controller-9knhj_default_8ae2f621-f360-11e4-8d12-54ee7527188d_7ec9aa3e', es.instance_variable_get(:@record_array)[0]['docker']['name']) assert_equal('fabric8-console-controller-9knhj', es.instance_variable_get(:@record_array)[0]['docker']['container_hostname']) assert_equal('b2bd1a24a68356b2f30128e6e28e672c1ef92df0d9ec01ec0c7faea5d77d2303', es.instance_variable_get(:@record_array)[0]['docker']['image_id']) assert_equal('fabric8/hawtio-kubernetes:latest', es.instance_variable_get(:@record_array)[0]['docker']['image']) end end test 'nonexistent docker metadata' do VCR.use_cassette('nonexistent_docker_metadata') do es = emit('', messages, '1111111111111111111111111111111111111111111111111111111111111111') assert_equal(4, es.instance_variable_get(:@record_array).size) assert_nil(es.instance_variable_get(:@record_array)[0]['docker']) end end end end
cosmo0920/fluent-plugin-docker_metadata_filter
test/helper.rb
<reponame>cosmo0920/fluent-plugin-docker_metadata_filter # # Fluentd Docker Metadata Filter Plugin - Enrich Fluentd events with Docker # metadata # # Copyright 2015 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # require "codeclimate-test-reporter" SimpleCov.start do formatter SimpleCov::Formatter::MultiFormatter.new [ SimpleCov::Formatter::HTMLFormatter, CodeClimate::TestReporter::Formatter ] end require 'rr' require 'test/unit' require 'test/unit/rr' require 'fileutils' require 'fluent/log' require 'fluent/test' require 'webmock/test_unit' require 'vcr' VCR.configure do |config| config.cassette_library_dir = "test/cassettes" config.hook_into :webmock # or :fakeweb config.ignore_hosts 'codeclimate.com' end unless defined?(Test::Unit::AssertionFailedError) class Test::Unit::AssertionFailedError < StandardError end end def unused_port s = TCPServer.open(0) port = s.addr[1] s.close port end def ipv6_enabled? require 'socket' begin TCPServer.open("::1", 0) true rescue false end end $log = Fluent::Log.new(Fluent::Test::DummyLogDevice.new, Fluent::Log::LEVEL_WARN)
jb41/smsapi-ruby
lib/smsapi.rb
<gh_stars>0 require 'smsapi/version' require 'net/http' module Smsapi class Client def initialize(username, password) @username = username @password = password end def send!(to, message) uri = URI('https://api.smsapi.pl/sms.do') Net::HTTP.post_form(uri, { "username" => @username, "password" => <PASSWORD>, "to" => to, # "fast" => "1", "message" => message }) end end end
bonomali/jruby_mahout
lib/jruby_mahout/data_model.rb
<reponame>bonomali/jruby_mahout module JrubyMahout class DataModel java_import org.apache.mahout.cf.taste.impl.model.file.FileDataModel attr_accessor :data_model def initialize(data_model_type, params) case data_model_type when "file" @data_model = FileDataModel.new(java.io.File.new(params[:file_path])) when "mysql" # TODO: implement @data_model = nil when "postgres" @data_model = PostgresManager.new(params).setup_data_model(params) else @data_model = nil end end end end
bonomali/jruby_mahout
lib/jruby_mahout/recommender_builder.rb
module JrubyMahout class RecommenderBuilder java_import org.apache.mahout.cf.taste.eval.RecommenderBuilder java_import org.apache.mahout.cf.taste.impl.similarity.PearsonCorrelationSimilarity java_import org.apache.mahout.cf.taste.impl.similarity.EuclideanDistanceSimilarity java_import org.apache.mahout.cf.taste.impl.similarity.SpearmanCorrelationSimilarity java_import org.apache.mahout.cf.taste.impl.similarity.LogLikelihoodSimilarity java_import org.apache.mahout.cf.taste.impl.similarity.TanimotoCoefficientSimilarity java_import org.apache.mahout.cf.taste.impl.similarity.PearsonCorrelationSimilarity java_import org.apache.mahout.cf.taste.impl.neighborhood.NearestNUserNeighborhood java_import org.apache.mahout.cf.taste.impl.neighborhood.ThresholdUserNeighborhood java_import org.apache.mahout.cf.taste.impl.recommender.GenericUserBasedRecommender java_import org.apache.mahout.cf.taste.impl.recommender.GenericItemBasedRecommender java_import org.apache.mahout.cf.taste.impl.recommender.slopeone.SlopeOneRecommender java_import org.apache.mahout.cf.taste.common.Weighting attr_accessor :recommender_name, :item_based_allowed # public interface RecommenderBuilder # Implementations of this inner interface are simple helper classes which create a Recommender to be evaluated based on the given DataModel. def initialize(similarity_name, neighborhood_size, recommender_name, is_weighted) @is_weighted = is_weighted @neighborhood_size = neighborhood_size @similarity_name = similarity_name @recommender_name = recommender_name @item_based_allowed = (@similarity_name == "SpearmanCorrelationSimilarity") ? false : true end # buildRecommender(DataModel dataModel) # Builds a Recommender implementation to be evaluated, using the given DataModel. def buildRecommender(data_model) begin case @similarity_name when "PearsonCorrelationSimilarity" similarity = (@is_weighted) ? PearsonCorrelationSimilarity.new(data_model, Weighting::WEIGHTED) : PearsonCorrelationSimilarity.new(data_model) when "EuclideanDistanceSimilarity" similarity = (@is_weighted) ? EuclideanDistanceSimilarity.new(data_model, Weighting::WEIGHTED) : EuclideanDistanceSimilarity.new(data_model) when "SpearmanCorrelationSimilarity" similarity = SpearmanCorrelationSimilarity.new(data_model) when "LogLikelihoodSimilarity" similarity = LogLikelihoodSimilarity.new(data_model) when "TanimotoCoefficientSimilarity" similarity = TanimotoCoefficientSimilarity.new(data_model) when "GenericItemSimilarity" similarity = PearsonCorrelationSimilarity.new(data_model, Weighting::WEIGHTED) else similarity = nil end unless @neighborhood_size.nil? if @neighborhood_size > 1 neighborhood = NearestNUserNeighborhood.new(Integer(@neighborhood_size), similarity, data_model) elsif @neighborhood_size >= -1 and @neighborhood_size <= 1 neighborhood = ThresholdUserNeighborhood.new(Float(@neighborhood_size), similarity, data_model) end end case @recommender_name when "GenericUserBasedRecommender" recommender = GenericUserBasedRecommender.new(data_model, neighborhood, similarity) when "GenericItemBasedRecommender" recommender = (@item_based_allowed) ? GenericItemBasedRecommender.new(data_model, similarity) : nil when "SlopeOneRecommender" recommender = SlopeOneRecommender.new(data_model) else recommender = nil end recommender rescue Exception => e return e end end end end
bonomali/jruby_mahout
lib/jruby_mahout/evaluator.rb
<filename>lib/jruby_mahout/evaluator.rb module JrubyMahout class Evaluator java_import org.apache.mahout.cf.taste.impl.eval.AverageAbsoluteDifferenceRecommenderEvaluator def initialize(data_model, recommender_builder) @data_model = data_model @recommender_builder = recommender_builder @mahout_evaluator = AverageAbsoluteDifferenceRecommenderEvaluator.new() end def evaluate(training_percentage, evaluation_percentage) if @recommender_builder.recommender_name == "GenericItemBasedRecommender" and !@recommender_builder.item_based_allowed nil else Float(@mahout_evaluator.evaluate(@recommender_builder, nil, @data_model, training_percentage, evaluation_percentage)) end end end end
bonomali/jruby_mahout
lib/jruby_mahout/postgres_manager.rb
module JrubyMahout class PostgresManager java_import org.apache.mahout.cf.taste.impl.model.jdbc.PostgreSQLJDBCDataModel begin java_import org.postgresql.ds.PGPoolingDataSource rescue Exception => e puts e end attr_accessor :data_model, :data_source, :statement def initialize(params) @data_source = PGPoolingDataSource.new() @data_source.setUser(params[:username]) @data_source.setPassword(params[:password]) @data_source.setServerName(params[:host]) @data_source.setPortNumber(params[:port]) @data_source.setDatabaseName(params[:db_name]) end def setup_data_model(params) begin @data_model = PostgreSQLJDBCDataModel.new(@data_source, params[:table_name], "user_id", "item_id", "rating", "created") rescue Exception => e puts e end end def create_statement begin connection = @data_source.getConnection() @statement = connection.createStatement() rescue Exception => e puts e end end def close_data_source begin @data_source.close() rescue Exception => e puts e end end def upsert_record(table_name, record) begin @statement.execute("UPDATE #{table_name} SET user_id=#{record[:user_id]}, item_id=#{record[:item_id]}, rating=#{record[:rating]} WHERE user_id=#{record[:user_id]} AND item_id=#{record[:item_id]};") @statement.execute("INSERT INTO #{table_name} (user_id, item_id, rating) SELECT #{record[:user_id]}, #{record[:item_id]}, #{record[:rating]} WHERE NOT EXISTS (SELECT 1 FROM #{table_name} WHERE user_id=#{record[:user_id]} AND item_id=#{record[:item_id]});") rescue java.sql.SQLException => e puts e end end def delete_record(table_name, record) begin @statement.execute("DELETE FROM #{table_name} WHERE user_id=#{record[:user_id]} AND item_id=#{record[:item_id]};") rescue java.sql.SQLException => e puts e end end def create_table(table_name) begin @statement.executeUpdate(" CREATE TABLE #{table_name} ( user_id BIGINT NOT NULL, item_id BIGINT NOT NULL, rating int NOT NULL, created TIMESTAMP DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (user_id, item_id) ); ") @statement.executeUpdate("CREATE INDEX #{table_name}_user_id_index ON #{table_name} (user_id);") @statement.executeUpdate("CREATE INDEX #{table_name}_item_id_index ON #{table_name} (item_id);") rescue java.sql.SQLException => e puts e end end def delete_table(table_name) begin @statement.executeUpdate("DROP INDEX IF EXISTS #{table_name}_user_id_index;") @statement.executeUpdate("DROP INDEX IF EXISTS #{table_name}_item_id_index;") @statement.executeUpdate("DROP TABLE IF EXISTS #{table_name};") rescue java.sql.SQLException => e puts e end end end end
bonomali/jruby_mahout
spec/recommender_spec.rb
<reponame>bonomali/jruby_mahout require 'spec_helper' describe JrubyMahout::Recommender do describe ".new" do context "with valid arguments" do it "should return an instance of JrubyMahout::Recommender for PearsonCorrelationSimilarity and GenericUserBasedRecommender" do JrubyMahout::Recommender.new("PearsonCorrelationSimilarity", 5, "GenericUserBasedRecommender", false).should be_an_instance_of JrubyMahout::Recommender end it "should return an instance of JrubyMahout::Recommender for EuclideanDistanceSimilarity and GenericUserBasedRecommender" do JrubyMahout::Recommender.new("EuclideanDistanceSimilarity", 5, "GenericUserBasedRecommender", false).should be_an_instance_of JrubyMahout::Recommender end it "should return an instance of JrubyMahout::Recommender for SpearmanCorrelationSimilarity and GenericUserBasedRecommender" do JrubyMahout::Recommender.new("SpearmanCorrelationSimilarity", 5, "GenericUserBasedRecommender", false).should be_an_instance_of JrubyMahout::Recommender end it "should return an instance of JrubyMahout::Recommender for LogLikelihoodSimilarity and GenericUserBasedRecommender" do JrubyMahout::Recommender.new("LogLikelihoodSimilarity", 5, "GenericUserBasedRecommender", false).should be_an_instance_of JrubyMahout::Recommender end it "should return an instance of JrubyMahout::Recommender for TanimotoCoefficientSimilarity and GenericUserBasedRecommender" do JrubyMahout::Recommender.new("TanimotoCoefficientSimilarity", 5, "GenericUserBasedRecommender", false).should be_an_instance_of JrubyMahout::Recommender end it "should return an instance of JrubyMahout::Recommender for GenericItemSimilarity and GenericUserBasedRecommender" do JrubyMahout::Recommender.new("GenericItemSimilarity", 5, "GenericUserBasedRecommender", false).should be_an_instance_of JrubyMahout::Recommender end it "should return an instance of JrubyMahout::Recommender for PearsonCorrelationSimilarity and GenericItemBasedRecommender" do JrubyMahout::Recommender.new("PearsonCorrelationSimilarity", nil, "GenericItemBasedRecommender", false).should be_an_instance_of JrubyMahout::Recommender end it "should return an instance of JrubyMahout::Recommender for EuclideanDistanceSimilarity and GenericItemBasedRecommender" do JrubyMahout::Recommender.new("EuclideanDistanceSimilarity", nil, "GenericItemBasedRecommender", false).should be_an_instance_of JrubyMahout::Recommender end it "should return an instance of JrubyMahout::Recommender for SpearmanCorrelationSimilarity and GenericItemBasedRecommender" do JrubyMahout::Recommender.new("SpearmanCorrelationSimilarity", nil, "GenericItemBasedRecommender", false).should be_an_instance_of JrubyMahout::Recommender end it "should return an instance of JrubyMahout::Recommender for LogLikelihoodSimilarity and GenericItemBasedRecommender" do JrubyMahout::Recommender.new("LogLikelihoodSimilarity", nil, "GenericItemBasedRecommender", false).should be_an_instance_of JrubyMahout::Recommender end it "should return an instance of JrubyMahout::Recommender for TanimotoCoefficientSimilarity and GenericItemBasedRecommender" do JrubyMahout::Recommender.new("TanimotoCoefficientSimilarity", nil, "GenericItemBasedRecommender", false).should be_an_instance_of JrubyMahout::Recommender end it "should return an instance of JrubyMahout::Recommender for GenericItemSimilarity and GenericItemBasedRecommender" do JrubyMahout::Recommender.new("GenericItemSimilarity", nil, "GenericItemBasedRecommender", false).should be_an_instance_of JrubyMahout::Recommender end it "should return an instance of JrubyMahout::Recommender for SlopeOneRecommender" do JrubyMahout::Recommender.new(nil, nil, "SlopeOneRecommender", false).should be_an_instance_of JrubyMahout::Recommender end end end describe "data_model=" do it "should load file data model" do recommender = JrubyMahout::Recommender.new("TanimotoCoefficientSimilarity", 5, "GenericUserBasedRecommender", false) recommender.data_model = JrubyMahout::DataModel.new("file", { :file_path => "spec/recommender_data.csv" }).data_model recommender.data_model.should be_an_instance_of org.apache.mahout.cf.taste.impl.model.file.FileDataModel end it "should load postgres data model" do recommender = JrubyMahout::Recommender.new("TanimotoCoefficientSimilarity", 5, "GenericUserBasedRecommender", false) recommender.data_model = JrubyMahout::DataModel.new("postgres", { :host => "localhost", :port => 5432, :db_name => "postgres", :username => "postgres", :password => "<PASSWORD>", :table_name => "taste_preferences" }).data_model recommender.data_model.should be_an_instance_of org.apache.mahout.cf.taste.impl.model.jdbc.PostgreSQLJDBCDataModel end end describe ".recommend" do context "with valid arguments" do context "with NearestNUserNeighborhood" do it "should return an array for PearsonCorrelationSimilarity and GenericUserBasedRecommender" do recommender = JrubyMahout::Recommender.new("PearsonCorrelationSimilarity", 5, "GenericUserBasedRecommender", false) recommender.data_model = JrubyMahout::DataModel.new("file", { :file_path => "spec/recommender_data.csv" }).data_model recommender.recommend(1, 10, nil).should be_an_instance_of Array end it "should return an array for EuclideanDistanceSimilarity and GenericUserBasedRecommender" do recommender = JrubyMahout::Recommender.new("EuclideanDistanceSimilarity", 5, "GenericUserBasedRecommender", false) recommender.data_model = JrubyMahout::DataModel.new("file", { :file_path => "spec/recommender_data.csv" }).data_model recommender.recommend(1, 10, nil).should be_an_instance_of Array end it "should return an array for SpearmanCorrelationSimilarity and GenericUserBasedRecommender" do recommender = JrubyMahout::Recommender.new("SpearmanCorrelationSimilarity", 5, "GenericUserBasedRecommender", false) recommender.data_model = JrubyMahout::DataModel.new("file", { :file_path => "spec/recommender_data.csv" }).data_model recommender.recommend(1, 10, nil).should be_an_instance_of Array end it "should return an array for LogLikelihoodSimilarity and GenericUserBasedRecommender" do recommender = JrubyMahout::Recommender.new("LogLikelihoodSimilarity", 5, "GenericUserBasedRecommender", false) recommender.data_model = JrubyMahout::DataModel.new("file", { :file_path => "spec/recommender_data.csv" }).data_model recommender.recommend(1, 10, nil).should be_an_instance_of Array end it "should return an array for TanimotoCoefficientSimilarity and GenericUserBasedRecommender" do recommender = JrubyMahout::Recommender.new("TanimotoCoefficientSimilarity", 5, "GenericUserBasedRecommender", false) recommender.data_model = JrubyMahout::DataModel.new("file", { :file_path => "spec/recommender_data.csv" }).data_model recommender.recommend(1, 10, nil).should be_an_instance_of Array end it "should return an array for GenericItemSimilarity and GenericUserBasedRecommender" do recommender = JrubyMahout::Recommender.new("GenericItemSimilarity", 5, "GenericUserBasedRecommender", false) recommender.data_model = JrubyMahout::DataModel.new("file", { :file_path => "spec/recommender_data.csv" }).data_model recommender.recommend(1, 10, nil).should be_an_instance_of Array end it "should return an array for PearsonCorrelationSimilarity and GenericItemBasedRecommender" do recommender = JrubyMahout::Recommender.new("PearsonCorrelationSimilarity", nil, "GenericItemBasedRecommender", false) recommender.data_model = JrubyMahout::DataModel.new("file", { :file_path => "spec/recommender_data.csv" }).data_model recommender.recommend(1, 10, nil).should be_an_instance_of Array end it "should return an array for EuclideanDistanceSimilarity and GenericItemBasedRecommender" do recommender = JrubyMahout::Recommender.new("EuclideanDistanceSimilarity", nil, "GenericItemBasedRecommender", false) recommender.data_model = JrubyMahout::DataModel.new("file", { :file_path => "spec/recommender_data.csv" }).data_model recommender.recommend(1, 10, nil).should be_an_instance_of Array end it "should return an array for LogLikelihoodSimilarity and GenericItemBasedRecommender" do recommender = JrubyMahout::Recommender.new("LogLikelihoodSimilarity", nil, "GenericItemBasedRecommender", false) recommender.data_model = JrubyMahout::DataModel.new("file", { :file_path => "spec/recommender_data.csv" }).data_model recommender.recommend(1, 10, nil).should be_an_instance_of Array end it "should return an array for TanimotoCoefficientSimilarity and GenericItemBasedRecommender" do recommender = JrubyMahout::Recommender.new("TanimotoCoefficientSimilarity", nil, "GenericItemBasedRecommender", false) recommender.data_model = JrubyMahout::DataModel.new("file", { :file_path => "spec/recommender_data.csv" }).data_model recommender.recommend(1, 10, nil).should be_an_instance_of Array end it "should return an array for GenericItemSimilarity and GenericItemBasedRecommender" do recommender = JrubyMahout::Recommender.new("GenericItemSimilarity", nil, "GenericItemBasedRecommender", false) recommender.data_model = JrubyMahout::DataModel.new("file", { :file_path => "spec/recommender_data.csv" }).data_model recommender.recommend(1, 10, nil).should be_an_instance_of Array end it "should return an array for SlopeOneRecommender" do recommender = JrubyMahout::Recommender.new("nil", nil, "SlopeOneRecommender", false) recommender.data_model = JrubyMahout::DataModel.new("file", { :file_path => "spec/recommender_data.csv" }).data_model recommender.recommend(1, 10, nil).should be_an_instance_of Array end end context "with ThresholdUserNeighborhood" do it "should return an array for PearsonCorrelationSimilarity and GenericUserBasedRecommender" do recommender = JrubyMahout::Recommender.new("PearsonCorrelationSimilarity", 0.7, "GenericUserBasedRecommender", false) recommender.data_model = JrubyMahout::DataModel.new("file", { :file_path => "spec/recommender_data.csv" }).data_model recommender.recommend(1, 10, nil).should be_an_instance_of Array end it "should return an array for EuclideanDistanceSimilarity and GenericUserBasedRecommender" do recommender = JrubyMahout::Recommender.new("EuclideanDistanceSimilarity", 0.7, "GenericUserBasedRecommender", false) recommender.data_model = JrubyMahout::DataModel.new("file", { :file_path => "spec/recommender_data.csv" }).data_model recommender.recommend(1, 10, nil).should be_an_instance_of Array end it "should return an array for SpearmanCorrelationSimilarity and GenericUserBasedRecommender" do recommender = JrubyMahout::Recommender.new("SpearmanCorrelationSimilarity", 0.7, "GenericUserBasedRecommender", false) recommender.data_model = JrubyMahout::DataModel.new("file", { :file_path => "spec/recommender_data.csv" }).data_model recommender.recommend(1, 10, nil).should be_an_instance_of Array end it "should return an array for LogLikelihoodSimilarity and GenericUserBasedRecommender" do recommender = JrubyMahout::Recommender.new("LogLikelihoodSimilarity", 0.7, "GenericUserBasedRecommender", false) recommender.data_model = JrubyMahout::DataModel.new("file", { :file_path => "spec/recommender_data.csv" }).data_model recommender.recommend(1, 10, nil).should be_an_instance_of Array end it "should return an array for TanimotoCoefficientSimilarity and GenericUserBasedRecommender" do recommender = JrubyMahout::Recommender.new("TanimotoCoefficientSimilarity", 0.7, "GenericUserBasedRecommender", false) recommender.data_model = JrubyMahout::DataModel.new("file", { :file_path => "spec/recommender_data.csv" }).data_model recommender.recommend(1, 10, nil).should be_an_instance_of Array end it "should return an array for GenericItemSimilarity and GenericUserBasedRecommender" do recommender = JrubyMahout::Recommender.new("GenericItemSimilarity", 0.7, "GenericUserBasedRecommender", false) recommender.data_model = JrubyMahout::DataModel.new("file", { :file_path => "spec/recommender_data.csv" }).data_model recommender.recommend(1, 10, nil).should be_an_instance_of Array end it "should return an array for PearsonCorrelationSimilarity and GenericItemBasedRecommender" do recommender = JrubyMahout::Recommender.new("PearsonCorrelationSimilarity", nil, "GenericItemBasedRecommender", false) recommender.data_model = JrubyMahout::DataModel.new("file", { :file_path => "spec/recommender_data.csv" }).data_model recommender.recommend(1, 10, nil).should be_an_instance_of Array end it "should return an array for EuclideanDistanceSimilarity and GenericItemBasedRecommender" do recommender = JrubyMahout::Recommender.new("EuclideanDistanceSimilarity", nil, "GenericItemBasedRecommender", false) recommender.data_model = JrubyMahout::DataModel.new("file", { :file_path => "spec/recommender_data.csv" }).data_model recommender.recommend(1, 10, nil).should be_an_instance_of Array end it "should return an array for LogLikelihoodSimilarity and GenericItemBasedRecommender" do recommender = JrubyMahout::Recommender.new("LogLikelihoodSimilarity", nil, "GenericItemBasedRecommender", false) recommender.data_model = JrubyMahout::DataModel.new("file", { :file_path => "spec/recommender_data.csv" }).data_model recommender.recommend(1, 10, nil).should be_an_instance_of Array end it "should return an array for TanimotoCoefficientSimilarity and GenericItemBasedRecommender" do recommender = JrubyMahout::Recommender.new("TanimotoCoefficientSimilarity", nil, "GenericItemBasedRecommender", false) recommender.data_model = JrubyMahout::DataModel.new("file", { :file_path => "spec/recommender_data.csv" }).data_model recommender.recommend(1, 10, nil).should be_an_instance_of Array end it "should return an array for GenericItemSimilarity and GenericItemBasedRecommender" do recommender = JrubyMahout::Recommender.new("GenericItemSimilarity", nil, "GenericItemBasedRecommender", false) recommender.data_model = JrubyMahout::DataModel.new("file", { :file_path => "spec/recommender_data.csv" }).data_model recommender.recommend(1, 10, nil).should be_an_instance_of Array end it "should return an array for SlopeOneRecommender" do recommender = JrubyMahout::Recommender.new("nil", nil, "SlopeOneRecommender", false) recommender.data_model = JrubyMahout::DataModel.new("file", { :file_path => "spec/recommender_data.csv" }).data_model recommender.recommend(1, 10, nil).should be_an_instance_of Array end end end context "with invalid arguments" do it "should return nil for SpearmanCorrelationSimilarity and GenericItemBasedRecommender" do recommender = JrubyMahout::Recommender.new("SpearmanCorrelationSimilarity", nil, "GenericItemBasedRecommender", false) recommender.data_model = JrubyMahout::DataModel.new("file", { :file_path => "spec/recommender_data.csv" }).data_model recommender.recommend(1, 10, nil).should be nil end end end describe ".evaluate" do context "with valid arguments" do it "should return a float" do recommender = JrubyMahout::Recommender.new("TanimotoCoefficientSimilarity", 5, "GenericUserBasedRecommender", false) recommender.data_model = JrubyMahout::DataModel.new("file", { :file_path => "spec/recommender_data.csv" }).data_model recommender.evaluate(0.7, 0.3).should be_an_instance_of Float end it "should return an array for PearsonCorrelationSimilarity and GenericUserBasedRecommender" do recommender = JrubyMahout::Recommender.new("PearsonCorrelationSimilarity", 5, "GenericUserBasedRecommender", false) recommender.data_model = JrubyMahout::DataModel.new("file", { :file_path => "spec/recommender_data.csv" }).data_model recommender.evaluate(0.7, 0.3).should be_an_instance_of Float end it "should return a float for EuclideanDistanceSimilarity and GenericUserBasedRecommender" do recommender = JrubyMahout::Recommender.new("EuclideanDistanceSimilarity", 5, "GenericUserBasedRecommender", false) recommender.data_model = JrubyMahout::DataModel.new("file", { :file_path => "spec/recommender_data.csv" }).data_model recommender.evaluate(0.7, 0.3).should be_an_instance_of Float end it "should return a float for SpearmanCorrelationSimilarity and GenericUserBasedRecommender" do recommender = JrubyMahout::Recommender.new("SpearmanCorrelationSimilarity", 5, "GenericUserBasedRecommender", false) recommender.data_model = JrubyMahout::DataModel.new("file", { :file_path => "spec/recommender_data.csv" }).data_model recommender.evaluate(0.7, 0.3).should be_an_instance_of Float end it "should return a float for LogLikelihoodSimilarity and GenericUserBasedRecommender" do recommender = JrubyMahout::Recommender.new("LogLikelihoodSimilarity", 5, "GenericUserBasedRecommender", false) recommender.data_model = JrubyMahout::DataModel.new("file", { :file_path => "spec/recommender_data.csv" }).data_model recommender.evaluate(0.7, 0.3).should be_an_instance_of Float end it "should return a float for TanimotoCoefficientSimilarity and GenericUserBasedRecommender" do recommender = JrubyMahout::Recommender.new("TanimotoCoefficientSimilarity", 5, "GenericUserBasedRecommender", false) recommender.data_model = JrubyMahout::DataModel.new("file", { :file_path => "spec/recommender_data.csv" }).data_model recommender.evaluate(0.7, 0.3).should be_an_instance_of Float end it "should return a float for GenericItemSimilarity and GenericUserBasedRecommender" do recommender = JrubyMahout::Recommender.new("GenericItemSimilarity", 5, "GenericUserBasedRecommender", false) recommender.data_model = JrubyMahout::DataModel.new("file", { :file_path => "spec/recommender_data.csv" }).data_model recommender.evaluate(0.7, 0.3).should be_an_instance_of Float end it "should return a float for PearsonCorrelationSimilarity and GenericItemBasedRecommender" do recommender = JrubyMahout::Recommender.new("PearsonCorrelationSimilarity", nil, "GenericItemBasedRecommender", false) recommender.data_model = JrubyMahout::DataModel.new("file", { :file_path => "spec/recommender_data.csv" }).data_model recommender.evaluate(0.7, 0.3).should be_an_instance_of Float end it "should return a float for EuclideanDistanceSimilarity and GenericItemBasedRecommender" do recommender = JrubyMahout::Recommender.new("EuclideanDistanceSimilarity", nil, "GenericItemBasedRecommender", false) recommender.data_model = JrubyMahout::DataModel.new("file", { :file_path => "spec/recommender_data.csv" }).data_model recommender.evaluate(0.7, 0.3).should be_an_instance_of Float end it "should return a float for LogLikelihoodSimilarity and GenericItemBasedRecommender" do recommender = JrubyMahout::Recommender.new("LogLikelihoodSimilarity", nil, "GenericItemBasedRecommender", false) recommender.data_model = JrubyMahout::DataModel.new("file", { :file_path => "spec/recommender_data.csv" }).data_model recommender.evaluate(0.7, 0.3).should be_an_instance_of Float end it "should return a float for TanimotoCoefficientSimilarity and GenericItemBasedRecommender" do recommender = JrubyMahout::Recommender.new("TanimotoCoefficientSimilarity", nil, "GenericItemBasedRecommender", false) recommender.data_model = JrubyMahout::DataModel.new("file", { :file_path => "spec/recommender_data.csv" }).data_model recommender.evaluate(0.7, 0.3).should be_an_instance_of Float end it "should return a float for GenericItemSimilarity and GenericItemBasedRecommender" do recommender = JrubyMahout::Recommender.new("GenericItemSimilarity", nil, "GenericItemBasedRecommender", false) recommender.data_model = JrubyMahout::DataModel.new("file", { :file_path => "spec/recommender_data.csv" }).data_model recommender.evaluate(0.7, 0.3).should be_an_instance_of Float end it "should return a float for SlopeOneRecommender" do recommender = JrubyMahout::Recommender.new("nil", nil, "SlopeOneRecommender", false) recommender.data_model = JrubyMahout::DataModel.new("file", { :file_path => "spec/recommender_data.csv" }).data_model recommender.evaluate(0.7, 0.3).should be_an_instance_of Float end end context "with invalid arguments" do it "should return nil for SpearmanCorrelationSimilarity and GenericItemBasedRecommender" do recommender = JrubyMahout::Recommender.new("SpearmanCorrelationSimilarity", nil, "GenericItemBasedRecommender", false) recommender.data_model = JrubyMahout::DataModel.new("file", { :file_path => "spec/recommender_data.csv" }).data_model recommender.evaluate(0.7, 0.3).should be nil end end end # TODO: cover all cases describe ".similar_users" do context "with valid arguments" do it "should return an array of users" do recommender = JrubyMahout::Recommender.new("SpearmanCorrelationSimilarity", 5, "GenericUserBasedRecommender", false) recommender.data_model = JrubyMahout::DataModel.new("file", { :file_path => "spec/recommender_data.csv" }).data_model recommender.similar_users(1, 10, nil).should be_an_instance_of Array end end end # TODO: cover all cases describe ".similar_items" do context "with valid arguments" do it "should return an array of items" do recommender = JrubyMahout::Recommender.new("GenericItemSimilarity", nil, "GenericItemBasedRecommender", false) recommender.data_model = JrubyMahout::DataModel.new("file", { :file_path => "spec/recommender_data.csv" }).data_model recommender.similar_items(4, 10, nil).should be_an_instance_of Array end end end # TODO: cover all cases describe ".recommended_because" do context "with valid arguments" do it "should return an array of items" do recommender = JrubyMahout::Recommender.new("PearsonCorrelationSimilarity", nil, "GenericItemBasedRecommender", false) recommender.data_model = JrubyMahout::DataModel.new("file", { :file_path => "spec/recommender_data.csv" }).data_model recommender.recommended_because(1, 138, 5).should be_an_instance_of Array end end end # TODO: cover all cases describe ".estimate_preference" do context "with valid arguments" do it "should return afloat with an estimate" do recommender = JrubyMahout::Recommender.new("PearsonCorrelationSimilarity", nil, "GenericItemBasedRecommender", false) recommender.data_model = JrubyMahout::DataModel.new("file", { :file_path => "spec/recommender_data.csv" }).data_model recommender.estimate_preference(1, 138).should be_an_instance_of Float end end end end
bonomali/jruby_mahout
lib/jruby_mahout/mysql_manager.rb
module JrubyMahout class MysqlManager # TODO: implement end end
bonomali/jruby_mahout
lib/jruby_mahout/recommender.rb
<gh_stars>0 module JrubyMahout class Recommender attr_accessor :is_weighted, :neighborhood_size, :similarity_name, :recommender_name, :data_model def initialize(similarity_name, neighborhood_size, recommender_name, is_weighted) @is_weighted = is_weighted @neighborhood_size = neighborhood_size @similarity_name = similarity_name @recommender_name = recommender_name @recommender_builder = RecommenderBuilder.new(@similarity_name, @neighborhood_size, @recommender_name, @is_weighted) @data_model = nil @recommender = nil end def data_model=(data_model) @data_model = data_model @recommender = @recommender_builder.buildRecommender(@data_model) end def recommend(user_id, number_of_items, rescorer) if @recommender.nil? nil else recommendations_to_array(@recommender.recommend(user_id, number_of_items, rescorer)) end end def evaluate(training_percentage, evaluation_percentage) evaluator = Evaluator.new(@data_model, @recommender_builder) evaluator.evaluate(training_percentage, evaluation_percentage) end def similar_items(item_id, number_of_items, rescorer) if @recommender.nil? or @recommender_name == "GenericUserBasedRecommender" nil else to_array(@recommender.mostSimilarItems(item_id, number_of_items, rescorer)) end end def similar_users(user_id, number_of_users, rescorer) if @recommender.nil? or @recommender_name == "GenericItemBasedRecommender" nil else to_array(@recommender.mostSimilarUserIDs(user_id, number_of_users, rescorer)) end end def estimate_preference(user_id, item_id) if @recommender.nil? nil else @recommender.estimatePreference(user_id, item_id) end end def recommended_because(user_id, item_id, number_of_items) if @recommender.nil? or @recommender_name == "GenericUserBasedRecommender" nil else to_array(@recommender.recommendedBecause(user_id, item_id, number_of_items)) end end private def recommendations_to_array(recommendations) recommendations_array = [] recommendations.each do |recommendation| recommendations_array << [recommendation.getItemID, recommendation.getValue.round(5)] end recommendations_array end private def to_array(things) things_array = [] things.each do |thing_id| things_array << thing_id end things_array end end end
bonomali/jruby_mahout
lib/jruby_mahout.rb
<reponame>bonomali/jruby_mahout module JrubyMahout require 'java' require File.join(ENV["MAHOUT_DIR"], 'mahout-core-0.7.jar') require File.join(ENV["MAHOUT_DIR"], 'mahout-integration-0.7.jar') require File.join(ENV["MAHOUT_DIR"], 'mahout-math-0.7.jar') Dir.glob(File.join(ENV["MAHOUT_DIR"], 'lib/*.jar')).each { |d| require d } require 'jruby_mahout/recommender' require 'jruby_mahout/recommender_builder' require 'jruby_mahout/data_model' require 'jruby_mahout/evaluator' require 'jruby_mahout/postgres_manager' require 'jruby_mahout/mysql_manager' end
bonomali/jruby_mahout
lib/jruby_mahout/version.rb
module JrubyMahout VERSION = '0.2.2' end
bonomali/jruby_mahout
jruby_mahout.gemspec
<filename>jruby_mahout.gemspec $:.push File.expand_path("../lib", __FILE__) require "jruby_mahout/version" Gem::Specification.new do |gem| gem.name = "jruby_mahout" gem.version = JrubyMahout::VERSION gem.authors = ["<NAME>"] gem.email = ["<EMAIL>"] gem.homepage = "https://github.com/vasinov/jruby_mahout" gem.summary = "JRuby Mahout is a gem that unleashes the power of Apache Mahout in the world of JRuby." gem.description = "JRuby Mahout is a gem that unleashes the power of Apache Mahout in the world of JRuby. Mahout is a superior machine learning library written in Java. It deals with recommendations, clustering and classification machine learning problems at scale. Until now it was difficult to use it in Ruby projects. You'd have to implement Java interfaces in Jruby yourself, which is not quick especially if you just started exploring the world of machine learning." gem.license = "MIT" gem.files = Dir["lib/**/*"] + ["MIT-LICENSE", "Rakefile", "README.md"] gem.test_files = Dir["spec/**/*"] gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) } gem.add_development_dependency "rake" gem.add_development_dependency "rspec" end
Alexx/food-review
spec/features/product_integration_spec.rb
<reponame>Alexx/food-review<filename>spec/features/product_integration_spec.rb require 'rails_helper' describe "the add a product and review process" do # FactoryBot.create(:user) it "adds a new product" do visit products_path click_link 'Create new product' fill_in 'Name', :with => 'Burrito' fill_in 'Cost', :with => 6 fill_in 'Country of origin', :with => 'Mexico' click_on 'Create Product' expect(page).to have_content 'Burrito' end it "gives error when no name is entered" do visit new_product_path click_on 'Create Product' expect(page).to have_content 'errors' end end
Alexx/food-review
app/models/review.rb
class Review < ApplicationRecord belongs_to :product validates :author, presence: true validates :content_body, presence: true validates :rating, presence: true validates_length_of :content_body, minimum: 50 validates_length_of :content_body, maximum: 250 before_save(:titleize_author) private def titleize_author self.author = self.author.titleize end end
Alexx/food-review
db/seeds.rb
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) Product.destroy_all 200.times do |index| product = Product.create!(name: Faker::Food.dish, country_of_origin: Faker::Address.country, cost: Faker::Number.between(from: 6, to: 30)) if product.persisted? rand(1..25).times do product.reviews.create( author: Faker::Name.name, content_body: Faker::Lorem.paragraph_by_chars(number: rand(50..250), supplemental: false), rating: rand(1..5) ) end end end p "Created #{Product.count} products."
Alexx/food-review
spec/models/product_spec.rb
<gh_stars>0 require 'rails_helper' describe Product do it { should have_many(:reviews) } it { should validate_presence_of :name } it { should validate_presence_of :cost } it { should validate_presence_of :country_of_origin } it("titleizes the name of a product") do product = Product.create({name: "meatball sandwich", cost: 8, country_of_origin: "United States"}) expect(product.name()).to(eq("Meatball Sandwich")) end end
Alexx/food-review
spec/factories.rb
require 'rails_helper' FactoryBot.define do factory :user do email {"<EMAIL>"} password{"<PASSWORD>"} password_confirmation{"<PASSWORD>"} end end
Alexx/food-review
app/controllers/reviews_controller.rb
<gh_stars>0 class ReviewsController < ApplicationController # before_action :authenticate_user!, :except => [:show, :index] def new @product = Product.find(params[:product_id]) @review = @product.reviews.new render :new end def create @product = Product.find(params[:product_id]) @review = @product.reviews.new(review_params) if @review.save flash[:notice] = "Review successfully added!" redirect_to product_path(@product) else render :new end end def show @product = Product.find(params[:product_id]) @review = Review.find(params[:id]) render :show end def edit @product = Product.find(params[:product_id]) @review = Review.find(params[:id]) render :edit end def update @review = Review.find(params[:id]) @product = Product.find(params[:product_id]) if @review.update(review_params) redirect_to product_path(@review.product) else render :edit end end def destroy @review = Review.find(params[:id]) @review.destroy redirect_to product_path(@review.product) end private def review_params params.require(:review).permit(:author, :content_body, :rating) end end
Alexx/food-review
spec/models/review_spec.rb
require 'rails_helper' describe Review do it { should belong_to(:product) } it { should validate_presence_of :author } it { should validate_presence_of :content_body } it { should validate_presence_of :rating } it { should validate_length_of(:content_body).is_at_least(50) } it { should validate_length_of(:content_body).is_at_most(250) } it("titleizes the name of a product") do product = Product.create({name: "meatball sandwich", cost: 8, country_of_origin: "United States"}) review = Review.create({author: "bill gates", content_body: "This is the best sandwich I have ever eaten, I would kiss a grizzly bear just to have another bite of one of these sandwichs!", rating: 5, product_id: product.id}) expect(review.author()).to(eq("<NAME>")) end end
Alexx/food-review
db/migrate/20190816174239_devise_create_admins.rb
# frozen_string_literal: true class DeviseCreateAdmins < ActiveRecord::Migration[5.2] def change create_table :admins do |t| t.string :email, :null => false, :default => "" t.string :encrypted_password, :null => false, :default => "" t.integer :sign_in_count, :default => 0 t.datetime :current_sign_in_at t.datetime :last_sign_in_at t.string :current_sign_in_ip t.string :last_sign_in_ip t.integer :failed_attempts, :default => 0 # Only if lock strategy is :failed_attempts t.string :unlock_token # Only if unlock strategy is :email or :both t.datetime :locked_at t.timestamps end end def self.down drop_table :admins end end
project-renard/homebrew-project-renard
Formula/curie.rb
require 'formula' class Curie < Formula class Perl510 < Requirement fatal true satisfy do `perl -E 'print $]'`.to_f >= 5.01000 end def message "Curie requires Perl 5.10.0 or greater." end end homepage 'https://project-renard.github.io/' desc "Document reader component from Project Renard" version '0.002' #url "http://cpan.cpantesters.org/authors/id/Z/ZM/ZMUGHAL/Renard-Curie-#{stable.version}.tar.gz" url "https://cpan.metacpan.org/authors/id/Z/ZM/ZMUGHAL/Renard-Curie-#{stable.version}.tar.gz" sha256 'c2a7673dfd34a335ed4ea61d7105c9b96163ce6b98b10ca5a764d5fd6598a42c' head 'https://github.com/project-renard/curie.git' depends_on Perl510 depends_on 'curie_dependencies' def install arch = %x(perl -MConfig -E 'print $Config{archname}') plib = "#{HOMEBREW_PREFIX}/lib/perl5" ENV['PERL5LIB'] = "#{plib}:#{plib}/#{arch}:#{lib}:#{lib}/#{arch}" ENV['PATH'] = "#{ENV['PATH']}:#{HOMEBREW_PREFIX}/bin" ENV.remove_from_cflags(/-march=\w+/) ENV.remove_from_cflags(/-msse\d?/) if build.head? || build.devel? plib = "#{prefix}/lib/perl5" ENV['PERL5LIB'] = "#{ENV['PERL5LIB']}:#{plib}:#{plib}/#{arch}:#{lib}:#{lib}/#{arch}" ENV['PATH'] = "#{ENV['PATH']}:#{prefix}/bin" system 'echo Append Formula/curie.rb' system 'echo PERL5LIB=$PERL5LIB' end system "cpanm --local-lib '#{prefix}' --notest Moose Function::Parameters" system "cpanm --local-lib '#{prefix}' --notest --installdeps ." if build.head? || build.devel? # Install any missing dependencies. system "cpanm --local-lib '#{prefix}' --notest Dist::Zilla" %w{authordeps}.each do |cmd| system "dzil #{cmd} | grep -v '^Possibly harmless' | cpanm --local-lib '#{prefix}' --notest" end # Build it in curie-HEAD and then cd into it. system "dzil build --in curie-HEAD" Dir.chdir 'curie-HEAD' # Remove perllocal.pod, simce it just gets in the way of other modules. rm "#{prefix}/lib/perl5/#{arch}/perllocal.pod", :force => true end system "cpanm --local-lib '#{prefix}' --notest --installdeps ." system "perl Makefile.PL INSTALL_BASE='#{prefix}'" system "make" # Add the Homebrew Perl lib dirs to curie. inreplace 'blib/script/curie' do |s| s.sub! /use /, "use lib '#{plib}', '#{plib}/#{arch}';\nuse " if `perl -E 'print $]'`.to_f == 5.01000 s.sub!(/ -CAS/, '') end end system "make install" end test do expected_version = stable.version.to_s got_version = shell_output("#{bin}/curie --version") assert_match expected_version, got_version end end
project-renard/homebrew-project-renard
Formula/curie_dependencies.rb
require 'formula' class CurieDependencies < Formula version '0.002' url "https://fastapi.metacpan.org/v1/source/ZMUGHAL/Renard-Curie-#{stable.version}/META.json", :using => :nounzip sha256 '1d9eafa402230afbcb1a9322d8f4275407271c57614fa0ef44c0c8f57a8cc855' homepage 'https://project-renard.github.io/' depends_on 'cpanminus' => :build depends_on :x11 # needed for Alien::MuPDF (builds mupdf-x11 on Mac OS X) depends_on 'gtk+3' depends_on 'gnome-icon-theme' #depends_on 'gtk-doc' depends_on 'clutter-gtk' depends_on 'gtk3-mac-integration' #depends_on 'gtksourceview3' #depends_on 'gtkspell3' #depends_on 'webkitgtk' def install system "mkdir -p #{prefix}/lib" system "touch #{prefix}/lib/keep-curie-dep" end end
HappyDevops/XsltRuby
lib/ModuleXSL.rb
# frozen_string_literal: true require 'nokogiri' module ModuleXSL # @return [String] def readFile(path) File.read(path) end # @return [String] def transform(xmlFile, xsltFile) xmlDocument = Nokogiri::XML(xmlFile) xsltDocument = Nokogiri::XSLT(xsltFile) xsltDocument.transform(xmlDocument).to_s end end
HappyDevops/XsltRuby
lib/main.rb
<reponame>HappyDevops/XsltRuby require_relative 'ModuleXSL' include ModuleXSL xmlFile = ModuleXSL::readFile('xmlDocument.xml') xsltFile = ModuleXSL::readFile('xsltDocument.xslt') puts ModuleXSL::transform(xmlFile, xsltFile)
joshweir/tormanager
lib/tormanager/eye/eye.tor.test.rb
<gh_stars>1-10 require 'eye' # Adding application Eye.application 'tormanager-tor-9250-1234' do # All options inherits down to the config leafs. # except `env`, which merging down # uid "user_name" # run app as a user_name (optional) - available only on ruby >= 2.0 # gid "group_name" # run app as a group_name (optional) - available only on ruby >= 2.0 #working_dir File.expand_path(File.join(File.dirname(__FILE__), %w[ processes ])) stdall '/tmp/tortrash.log' # stdout,err logs for processes by default #env 'APP_ENV' => 'production' # global env for each processes trigger :flapping, times: 10, within: 1.minute, retry_in: 10.minutes check :cpu, every: 30.seconds, below: 10, times: 3 # global check for all processes check :memory, every: 60.seconds, below: 200.megabytes, times: 3 process :sample1 do pid_file '1.pid' # pid_path will be expanded with the working_dir start_command "tor --SocksPort 9250 --ControlPort 52500 " + "--CookieAuthentication 0 --HashedControlPassword \"<PASSWORD>" + "<PASSWORD>\" --NewCircuitPeriod " + "60 --DataDirectory /tmp/tor_data/9250/ --Log \"notice syslog\"" daemonize true #stdall 'sample1.log' end =begin group 'samples' do chain grace: 5.seconds # chained start-restart with 5s interval, one by one. end =end end
joshweir/tormanager
spec/tormanager_spec.rb
require "spec_helper" RSpec.describe TorManager do it "has a version number" do expect(TorManager::VERSION).not_to be nil end end
joshweir/tormanager
lib/tormanager/process_helper.rb
require 'socket' module TorManager CannotKillProcess = Class.new(StandardError) class ProcessHelper class << self def query_process query return [] unless query query_process_bash_cmd(query).split("\n").map{ |query_output_line| get_pid_from_query_process_output_line(query_output_line) }.compact end def kill_process pids to_array(pids).each do |pid| try_to_kill pid: Integer(pid), attempts: 5 end end def process_pid_running? pid begin return false if pid.to_s == ''.freeze ipid = Integer(pid) return false if ipid <= 0 Process.kill(0, ipid) return true rescue return false end end def port_is_open? port begin server = TCPServer.new('127.0.0.1', port) server.close return true rescue Errno::EADDRINUSE; return false end end private def query_process_bash_cmd query `ps -ef | #{query_grep_pipe_chain(query)} | grep -v grep` end def query_grep_pipe_chain query to_array(query) .map{|q| "grep '#{q}'"} .join(' | ') end def get_pid_from_query_process_output_line query_output_line output_parts = query_output_line.gsub(/\s\s+/, ' ').strip.split output_parts.size >= 3 && output_parts[1].to_i > 0 ? output_parts[1].to_i : nil end def to_array v (v.kind_of?(Array) ? v : [v]) end def try_to_kill params={} pid = params.fetch(:pid, nil) return unless pid && process_pid_running?(pid) params.fetch(:attempts, 5).times do |i| i < 3 ? Process.kill('TERM', pid) : Process.kill('KILL', pid) sleep 0.5 break unless process_pid_running? pid raise CannotKillProcess, "Couldnt kill pid: #{pid}" if i >= 4 end end end end end
joshweir/tormanager
spec/tormanager/create_eye_config_spec.rb
<filename>spec/tormanager/create_eye_config_spec.rb<gh_stars>1-10 require "spec_helper" module TorManager describe CreateEyeConfig do subject { CreateEyeConfig.new( eye_tor_config_path: '/tmp/tor.config.eye.rb', eye_tor_config_template: File.join(File.expand_path('../../..', __FILE__), 'lib/tormanager/eye/tor.template.eye.rb'), tor_port: 9050, control_port: 50500, pid_dir: '/tmp', log_dir: '/tmp', tor_data_dir: nil, tor_new_circuit_period: 60, max_tor_memory_usage_mb: 200, max_tor_cpu_percentage: 10, eye_logging: nil, tor_logging: nil, parent_pid: 12345, hashed_control_password: '<PASSWORD>', tor_log_switch: 'notice syslog' ) } let(:config_template_content) { %Q(require 'eye' if %w(true 1).include?('[[[eye_logging]]]') Eye.config do logger File.join('[[[log_dir]]]', 'tormanager.eye.log') end end Eye.application 'tormanager-tor-[[[tor_port]]]-[[[parent_pid]]]' do stdall File.join('[[[log_dir]]]', 'tormanager-tor-[[[tor_port]]]-[[[parent_pid]]].log') if %w(true 1).include?('[[[tor_logging]]]') trigger :flapping, times: 10, within: 1.minute, retry_in: 10.minutes check :cpu, every: 30.seconds, below: [[[max_tor_cpu_percentage]]], times: 3 check :memory, every: 60.seconds, below: [[[max_tor_memory_usage_mb]]].megabytes, times: 3 process :tor do pid_file File.join('[[[pid_dir]]]', 'tormanager-tor-[[[tor_port]]]-[[[parent_pid]]].pid') start_command "tor --SocksPort [[[tor_port]]] --ControlPort [[[control_port]]] " + "--CookieAuthentication 0 --HashedControlPassword \"[[[hashed_control_password]]]\" --NewCircuitPeriod " + "[[[tor_new_circuit_period]]] " + ('[[[tor_data_dir]]]'.length > 0 ? "--DataDirectory #{File.join('[[[tor_data_dir]]]', '[[[tor_port]]]')} " : "") + ('[[[tor_log_switch]]]'.length > 0 ? "--Log \"[[[tor_log_switch]]]\" " : "") daemonize true end end) } let(:expected_config_content) { %Q(require 'eye' if %w(true 1).include?('') Eye.config do logger File.join('/tmp', 'tormanager.eye.log') end end Eye.application 'tormanager-tor-9050-12345' do stdall File.join('/tmp', 'tormanager-tor-9050-12345.log') if %w(true 1).include?('') trigger :flapping, times: 10, within: 1.minute, retry_in: 10.minutes check :cpu, every: 30.seconds, below: 10, times: 3 check :memory, every: 60.seconds, below: 200.megabytes, times: 3 process :tor do pid_file File.join('/tmp', 'tormanager-tor-9050-12345.pid') start_command "tor --SocksPort 9050 --ControlPort 50500 " + "--CookieAuthentication 0 --HashedControlPassword \"<PASSWORD>\" --NewCircuitPeriod " + "60 " + (''.length > 0 ? "--DataDirectory /9050 " : "") + ('notice syslog'.length > 0 ? "--Log \"notice syslog\" " : "") daemonize true end end) } describe '#create' do it 'reads the :eye_tor_config_template, substitutes param keywords ' + 'and writes to :eye_tor_config_path' do file = double('file') allow(File) .to receive(:read) .with(File.join(File.expand_path('../../..', __FILE__), 'lib/tormanager/eye/tor.template.eye.rb')) .and_return(config_template_content) allow(File) .to receive(:open) .with("/tmp/tor.config.eye.rb", "w") .and_yield(file) expect(file).to receive(:puts).with(expected_config_content) subject.create end end end end
joshweir/tormanager
spec/tormanager/tor_process_spec.rb
<gh_stars>1-10 require "spec_helper" module TorManager describe TorProcess do #before do # allow_any_instance_of(TorProcess).to receive(:`) # .with("tor --quiet --hash-password '<PASSWORD>'") # .and_return('16:foo') #end context 'when initialized with default params' do before do # allow_any_instance_of(TorProcess).to receive(:`) # .with("tor --quiet --hash-password '<PASSWORD>'") # .and_return('16:foo') allow(SecureRandom) .to receive_message_chain('random_number.to_s.rjust') .and_return('<PASSWORD>') end it "initializes with default parameters" do expect(subject.settings[:tor_port]).to eq 9050 expect(subject.settings[:control_port]).to eq 50500 expect(subject.settings[:pid_dir]).to eq '/tmp' expect(subject.settings[:log_dir]).to eq '/tmp' expect(subject.settings[:tor_data_dir]).to be_nil expect(subject.settings[:tor_new_circuit_period]).to eq 60 expect(subject.settings[:max_tor_memory_usage_mb]).to eq 200 expect(subject.settings[:max_tor_cpu_percentage]).to eq 10 expect(subject.settings[:eye_tor_config_template]) .to eq File.join(File.expand_path('../../..', __FILE__), 'lib/tormanager/eye/tor.template.eye.rb') expect(subject.settings[:control_password]).to eq '<PASSWORD>' expect(subject.settings[:hashed_control_password][0..2]) .to eq '16:' expect(subject.settings[:tor_log_switch]).to be_nil expect(subject.settings[:tor_logging]).to be_nil expect(subject.settings[:eye_logging]).to be_nil expect(subject.settings[:dont_remove_tor_config]).to be_nil end it "generates a random control_password (between 8 and 16 chars) " + "and a hash_control_password when none specified" do expect(subject.settings[:control_password].length).to eq 12 expect(subject.settings[:hashed_control_password][0..2]) .to eq '16:' end end context 'when initialized with user params' do let(:subject) { TorProcess.new control_password: '<PASSWORD>', tor_port: 9350, control_port: 53700, tor_logging: true, eye_logging: true, tor_data_dir: '/tmp/tor_data', tor_log_switch: 'notice syslog' } it "initializes with user parameters" do expect(subject.settings[:tor_port]).to eq 9350 expect(subject.settings[:control_port]).to eq 53700 expect(subject.settings[:tor_data_dir]).to eq '/tmp/tor_data' expect(subject.settings[:tor_log_switch]).to eq 'notice syslog' expect(subject.settings[:tor_logging]).to be_truthy expect(subject.settings[:eye_logging]).to be_truthy end it "should generate a hashed_control_password based on user specified control_password" do expect(subject.settings[:control_password]).to eq '<PASSWORD>' expect(subject.settings[:hashed_control_password][0..2]) .to eq '16:' end end describe "#start" do it "validates that the tor control port is open" do allow(ProcessHelper).to receive(:port_is_open?).with(50700).and_return(false) allow(ProcessHelper).to receive(:port_is_open?).with(52700).and_return(true) expect{TorProcess.new(tor_port: 52700, control_port: 50700).start} .to raise_error(TorManager::TorControlPortInUse) end it "validates that the tor port is open" do allow(ProcessHelper).to receive(:port_is_open?).with(9250).and_return(false) allow(ProcessHelper).to receive(:port_is_open?).with(53700).and_return(true) expect{TorProcess.new(tor_port: 9250, control_port: 53700).start} .to raise_error(TorManager::TorPortInUse) end context 'when initialized with default params' do it "creates a Tor eye config, starts Tor and verifies Tor is up" do allow_tor_ports_to_be_open subject.settings expect_eye_config_to_be_created_with subject.settings expect_eye_manager_to_issue_start_with subject.settings expect_eye_manager_to_report_tor_is_up subject.settings subject.start end it "throws exception if Tor does not come up after timeout" do allow_tor_ports_to_be_open subject.settings expect_eye_config_to_be_created_with subject.settings expect_eye_manager_to_issue_start_with subject.settings expect_eye_manager_to_report_tor_is_not_up subject.settings expect{subject.start} .to raise_error(TorManager::TorFailedToStart, /Tor didnt start up after 20 seconds! See log: \/tmp\/tormanager-tor-\d+-\d+.log/) end end context 'when initialized with user params' do let(:subject) { TorProcess.new control_password: '<PASSWORD>', tor_port: 9350, control_port: 53700, tor_logging: true, eye_logging: true, tor_data_dir: '/tmp/tor_data', tor_log_switch: 'notice syslog' } it "creates a Tor eye config, starts Tor and verifies Tor is up" do allow_tor_ports_to_be_open subject.settings expect_eye_config_to_be_created_with subject.settings expect_eye_manager_to_issue_start_with subject.settings expect_eye_manager_to_report_tor_is_up subject.settings subject.start end end end describe "#stop" do context 'when initialized with default params' do it 'issues EyeManager stop orders' do expect_eye_manager_to_issue_stop_with subject.settings expect_eye_manager_to_report_tor_is 'unmonitored', subject.settings subject.stop end it 'deletes the eye tor config file if it exists' do expect_eye_manager_to_issue_stop_with subject.settings expect_eye_manager_to_report_tor_is 'unmonitored', subject.settings eye_config = eye_config_path(subject.settings) allow(File).to receive(:exists?).with(eye_config).and_return(true) expect(File).to receive(:delete).with(eye_config) subject.stop end it 'doesnt try to delete the config file if it does not exist' do expect_eye_manager_to_issue_stop_with subject.settings expect_eye_manager_to_report_tor_is 'unmonitored', subject.settings eye_config = eye_config_path(subject.settings) allow(File).to receive(:exists?).with(eye_config).and_return(false) expect(File).to_not receive(:delete) subject.stop end it 'checks that tor is stopped through Eye status: unmonitored' do expect_eye_manager_to_issue_stop_with subject.settings expect_eye_manager_to_report_tor_is 'unmonitored', subject.settings subject.stop end it 'checks that tor is stopped through Eye status: unknown' do expect_eye_manager_to_issue_stop_with subject.settings expect_eye_manager_to_report_tor_is 'unknown', subject.settings subject.stop end it 'throws exception if Tor does not stop after timeout' do expect_eye_manager_to_issue_stop_with subject.settings expect_eye_manager_to_report_tor_is_not_down subject.settings expect{subject.stop} .to raise_error(TorManager::TorFailedToStop, /Tor didnt stop after 20 seconds! Last status: up See log: \/tmp\/tormanager-tor-\d+-\d+.log/) end end context 'when initialized with different tor and control port' do let(:subject) { TorProcess.new tor_port: 9350, control_port: 53700 } it 'it stops the Tor process the same as would with default params' do expect_eye_manager_to_issue_stop_with subject.settings expect_eye_manager_to_report_tor_is 'unmonitored', subject.settings subject.stop end end context 'when initialized with :dont_remove_tor_config = true' do let(:subject) { TorProcess.new dont_remove_tor_config: true } it 'does not delete the eye tor config file' do expect_eye_manager_to_issue_stop_with subject.settings expect_eye_manager_to_report_tor_is 'unmonitored', subject.settings expect(File).to_not receive(:exists?) expect(File).to_not receive(:delete) subject.stop end end end describe ".stop_obsolete_processes" do context "when there are tor processes being monitored by Eye" do it 'will issue EyeManager.stop if the tor process is running' do allow(EyeManager) .to receive(:list_apps) .and_return( %w(tormanager-tor-9050-1 tormanager-tor-9050-2)) #simulate that only the first tor process is running allow(ProcessHelper) .to receive(:process_pid_running?).and_return(true, false) expect(EyeManager) .to_not receive(:stop).with(application: "tormanager-tor-9050-1", process: "tor") expect(EyeManager) .to receive(:stop).with(application: "tormanager-tor-9050-2", process: "tor") TorProcess.stop_obsolete_processes end end context "when there are no tor processes being monitored by Eye" do it "does not proceed to check any EyeManager processes" do allow(EyeManager).to receive(:list_apps).and_return(nil) expect(ProcessHelper).to_not receive(:process_pid_running?) expect(EyeManager).to_not receive(:stop) TorProcess.stop_obsolete_processes end end end describe ".tor_running_on?" do context "when there are tor processes being monitored by Eye" do it "is true if Tor is running on port" do setup_tor_running_on_example expect(TorProcess.tor_running_on?(port: 9050)).to be_truthy end it "is false if Tor is not running on port" do setup_tor_running_on_example expect(TorProcess.tor_running_on?(port: 9051)).to be_falsey expect(TorProcess.tor_running_on?(port: 9052)).to be_falsey end it "is true if checking port and parent pid and both match" do setup_tor_running_on_example expect(TorProcess.tor_running_on?(port: 9050, parent_pid: 2)).to be_truthy end it "is false if port matches but parent pid does not" do setup_tor_running_on_example expect(TorProcess.tor_running_on?(port: 9050, parent_pid: 1)).to be_falsey end it "is true if parent pid matches" do setup_tor_running_on_example expect(TorProcess.tor_running_on?(parent_pid: 2)).to be_truthy end it "is false if called with no :port or :parent_pid" do setup_tor_running_on_example expect(TorProcess.tor_running_on?).to be_falsey end end context "when there are no tor processes being monitored by Eye" do it "is false" do allow(EyeManager).to receive(:list_apps).and_return(nil) expect(EyeManager).to_not receive(:status) expect(TorProcess.tor_running_on?(port: 9050)) .to be_falsey end end end def expect_eye_config_to_be_created_with settings eye_config = double("eye_config") expect(CreateEyeConfig) .to receive(:new) .with(:tor_port=>settings[:tor_port], :control_port=>settings[:control_port], :pid_dir=>settings[:pid_dir], :log_dir=>settings[:log_dir], :tor_data_dir=>settings[:tor_data_dir], :tor_new_circuit_period=>settings[:tor_new_circuit_period], :max_tor_memory_usage_mb=>settings[:max_tor_memory_usage_mb], :max_tor_cpu_percentage=>settings[:max_tor_cpu_percentage], :eye_tor_config_template=>settings[:eye_tor_config_template], :parent_pid=>settings[:parent_pid], :control_password=>settings[:control_password], :hashed_control_password=>settings[:hashed_control_password], :tor_log_switch=>settings[:tor_log_switch], :eye_logging=>settings[:eye_logging], :tor_logging=>settings[:tor_logging], :dont_remove_tor_config=>settings[:dont_remove_tor_config], :eye_tor_config_path=>eye_config_path(settings)) .and_return(eye_config) expect(eye_config).to receive(:create) end def expect_eye_manager_to_issue_start_with settings expect(EyeManager) .to receive(:start) .with(config: "/tmp/tormanager.tor" + ".#{settings[:tor_port]}.#{settings[:parent_pid]}.eye.rb", application: eye_app_name(settings)) end def expect_eye_manager_to_issue_stop_with settings expect(EyeManager) .to receive(:stop) .with(application: eye_app_name(settings), process: 'tor') end def expect_eye_manager_to_report_tor_is_up settings allow(subject).to receive(:sleep) expect(EyeManager) .to receive(:status) .with(application: eye_app_name(settings), process: 'tor') .and_return('down','down','down','down','down', 'down','down','down','down','up') end def expect_eye_manager_to_report_tor_is_not_up settings allow(subject).to receive(:sleep) expect(EyeManager) .to receive(:status) .with(application: eye_app_name(settings), process: 'tor') .and_return('down','down','down','down','down', 'down','down','down','down','down') end def expect_eye_manager_to_report_tor_is down_status, settings allow(subject).to receive(:sleep) expect(EyeManager) .to receive(:status) .with(application: eye_app_name(settings), process: 'tor') .and_return('up','up','up','up','up', 'up','up','up','up',down_status) end def expect_eye_manager_to_report_tor_is_not_down settings allow(subject).to receive(:sleep) expect(EyeManager) .to receive(:status) .with(application: eye_app_name(settings), process: 'tor') .and_return('up','up','up','up','up', 'up','up','up','up','up') end def eye_app_name settings "tormanager-tor-#{settings[:tor_port]}-#{settings[:parent_pid]}" end def eye_config_path settings File.join( settings[:log_dir], "tormanager.tor.#{settings[:tor_port]}.#{settings[:parent_pid]}.eye.rb") end def allow_tor_ports_to_be_open settings allow(ProcessHelper) .to receive(:port_is_open?) .with(settings[:tor_port]).and_return(true) allow(ProcessHelper) .to receive(:port_is_open?) .with(settings[:control_port]).and_return(true) end def setup_tor_running_on_example allow(EyeManager).to receive(:list_apps).and_return( %w(tormanager-tor-9051-1 tormanager-tor-9050-2)) allow(EyeManager) .to receive(:status) .with(application: "tormanager-tor-9051-1", process: 'tor') .and_return('unmonitored') allow(EyeManager) .to receive(:status) .with(application: "tormanager-tor-9050-2", process: 'tor') .and_return('up') end end end
joshweir/tormanager
lib/tormanager/tor_process.rb
<reponame>joshweir/tormanager require 'eye' require 'eyemanager' require 'fileutils' require 'securerandom' module TorManager Error = Class.new(StandardError) TorPortInUse = Class.new(Error) TorControlPortInUse = Class.new(Error) TorFailedToStart = Class.new(Error) TorFailedToStop = Class.new(Error) class TorProcess attr_accessor :settings def initialize params={} @settings = {} @settings[:tor_port] = params.fetch(:tor_port, 9050) @settings[:control_port] = params.fetch(:control_port, 50500) @settings[:pid_dir] = params.fetch(:pid_dir, '/tmp'.freeze) @settings[:log_dir] = params.fetch(:log_dir, '/tmp'.freeze) @settings[:tor_data_dir] = params.fetch(:tor_data_dir, nil) @settings[:tor_new_circuit_period] = params.fetch(:tor_new_circuit_period, 60) @settings[:max_tor_memory_usage_mb] = params.fetch(:max_tor_memory_usage, 200) @settings[:max_tor_cpu_percentage] = params.fetch(:max_tor_cpu_percentage, 10) @settings[:eye_tor_config_template] = params.fetch(:eye_tor_config_template, File.join(File.dirname(__dir__),'tormanager/eye/tor.template.eye.rb')) @settings[:parent_pid] = Process.pid @settings[:control_password] = params.fetch(:control_password, <PASSWORD>) @settings[:hashed_control_password] = tor_hash_password_from(@settings[:control_password]) @settings[:tor_log_switch] = params.fetch(:tor_log_switch, nil) @settings[:eye_logging] = params.fetch(:eye_logging, nil) @settings[:tor_logging] = params.fetch(:tor_logging, nil) @settings[:dont_remove_tor_config] = params.fetch(:dont_remove_tor_config, nil) end def start prepare_tor_start_and_monitor if tor_ports_are_open? end def stop EyeManager.stop application: eye_app_name, process: 'tor' remove_eye_tor_config unless @settings[:dont_remove_tor_config] ensure_tor_is_down end class << self def stop_obsolete_processes (EyeManager.list_apps || []).each do |app| EyeManager.stop(application: app, process: 'tor') unless ProcessHelper.process_pid_running? pid_of_tor_eye_process(app) end end def tor_running_on? params={} is_running = false (EyeManager.list_apps || []).each do |app| if port_and_or_pid_matches_eye_tor_name?(app, params) && EyeManager.status(application: app, process: 'tor') == 'up' is_running = true break end end is_running end private def port_and_or_pid_matches_eye_tor_name? app, params={} (params[:port] || params[:parent_pid]) && (!params[:port] || port_of_tor_eye_process(app).to_i == params[:port].to_i) && (!params[:parent_pid] || pid_of_tor_eye_process(app).to_i == params[:parent_pid].to_i) end def pid_of_tor_eye_process app app.to_s.split('-').last end def port_of_tor_eye_process app app_name_split = app.to_s.split('-') app_name_split.length >= 3 ? app_name_split[2].to_i : nil end end private def tor_ports_are_open? tor_port_is_open? && control_port_is_open? end def tor_port_is_open? raise TorPortInUse, "Cannot spawn Tor process as port " + "#{@settings[:tor_port]} is in use" unless ProcessHelper.port_is_open?(@settings[:tor_port]) true end def control_port_is_open? raise TorControlPortInUse, "Cannot spawn Tor process as control port " + "#{@settings[:control_port]} is in use" unless ProcessHelper.port_is_open?(@settings[:control_port]) true end def prepare_tor_start_and_monitor #build_eye_config_from_template eye_config = CreateEyeConfig.new( @settings.merge( eye_tor_config_path: eye_config_filename)) eye_config.create make_dirs start_tor_and_monitor end def eye_config_filename @eye_config_filename || File.join(@settings[:log_dir], "tormanager.tor.#{@settings[:tor_port]}.#{Process.pid}.eye.rb") end def eye_app_name @eye_app_name || "tormanager-tor-#{@settings[:tor_port]}-#{Process.pid}" end def make_dirs [@settings[:log_dir], @settings[:pid_dir], @settings[:tor_data_dir]].each do |path| FileUtils.mkpath(path) if path && !File.exists?(path) end end def start_tor_and_monitor EyeManager.start config: eye_config_filename, application: eye_app_name ensure_tor_is_up end def ensure_tor_is_up 10.times do |i| break if EyeManager.status( application: eye_app_name, process: 'tor') == 'up' sleep 2 raise TorFailedToStart, "Tor didnt start up after 20 seconds! See log: " + "#{File.join(@settings[:log_dir], eye_app_name + ".log")}" if i >= 9 end end def ensure_tor_is_down 10.times do |i| tor_status = EyeManager.status( application: eye_app_name, process: 'tor') break if ['unknown','unmonitored'].include?(tor_status) sleep 2 raise TorFailedToStop, "Tor didnt stop after 20 seconds! Last status: #{tor_status} See log: " + "#{File.join(@settings[:log_dir], eye_app_name + ".log")}" if i >= 9 end end def remove_eye_tor_config File.delete(eye_config_filename) if File.exists?(eye_config_filename) end def random_password SecureRandom.random_number(36**12).to_s(36).rjust(12, "0") end def tor_hash_password_from password `tor --quiet --hash-password '#{password}'`.strip end end end
joshweir/tormanager
lib/tormanager.rb
<gh_stars>1-10 require "tormanager/version" require "tormanager/process_helper" require "tormanager/control" require "tormanager/tor_process" require "tormanager/proxy" require "tormanager/ip_address_control" require "tormanager/create_eye_config"
joshweir/tormanager
spec/features/ip_address_control_spec.rb
require "spec_helper" module TorManager describe IpAddressControl do let(:tor_process) { TorManager::TorProcess.new tor_port: 9350, control_port: 53500 } let(:tor_proxy) { Proxy.new tor_process: tor_process } let(:tor_ip_control) { IpAddressControl.new tor_process: tor_process, tor_proxy: tor_proxy} before :all do EyeManager.destroy end after :all do EyeManager.destroy end describe "#get_ip" do it "raises exception if Tor is not available on specified port" do expect{tor_ip_control.get_ip}.to raise_error /Tor is not running on port 9350/ end it "gets the current ip" do tor_process.start expect(tor_ip_control.get_ip).to match(/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/) end end describe "#get_new_ip" do it "raises exception if Tor is not available on specified port" do tor_process.stop expect{tor_ip_control.get_new_ip}.to raise_error /Tor is not running on port 9350/ end it "gets a new ip" do tor_process.start previous_ip = tor_ip_control.get_ip expect(previous_ip).to match(/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/) new_ip = tor_ip_control.get_new_ip expect(new_ip).not_to eq previous_ip expect(new_ip).to match(/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/) end end end end
joshweir/tormanager
spec/tormanager/control_spec.rb
<reponame>joshweir/tormanager<filename>spec/tormanager/control_spec.rb require "spec_helper" module Tor describe Controller do describe '.connect' do context 'with default params' do it 'initializes itself with default params' do expected = {host: '127.0.0.1', port: 9051} mockSocket = double('socket') expect(TCPSocket).to receive(:new) .with(expected[:host], expected[:port]) .and_return(mockSocket) expect(mockSocket).to receive(:setsockopt) subject = Controller.connect actual = {host: subject.host, port: subject.port} expect(actual).to eq expected end end context 'with specified params' do it 'initializes itself with specified params' do expected = {host: '127.0.0.2', port: 9052} mockSocket = double('socket') expect(TCPSocket).to receive(:new) .with(expected[:host], expected[:port]) .and_return(mockSocket) expect(mockSocket).to receive(:setsockopt) subject = Controller.connect expected actual = {host: subject.host, port: subject.port} expect(actual).to eq expected end end context 'calling connect multiple times' do it 'closes the socket before re-connecting if already connected' do mockSocket = double('socket') mockSocket2 = double('socket2') expect(TCPSocket).to receive(:new) .and_return(mockSocket, mockSocket2) allow(mockSocket).to receive(:setsockopt) allow(mockSocket2).to receive(:setsockopt) expect(mockSocket).to receive(:close) subject = Controller.connect subject.connect end end context 'with a block' do it 'calls the block' do expected = {host: '127.0.0.1', port: 9051} mockSocket = double('socket') allow(TCPSocket).to receive(:new).and_return(mockSocket) allow(mockSocket).to receive(:setsockopt) #mock the tor.signal shell expect_any_instance_of(Controller).to receive(:send_command).once expect_any_instance_of(Controller).to receive(:read_reply).twice expect_any_instance_of(Controller).to receive(:send_line).once expect(mockSocket).to receive(:close) Tor::Controller.connect do |tor| tor.signal("newnym") end end end end describe '#connected?' do context 'when Controller is connected' do it 'is truthy' do subject, socket = default_controller_connect .values_at(:controller, :socket) expect(subject.connected?).to be_truthy end end context 'when Controller is not connected' do it 'is falsy' do subject = close_controller(default_controller_connect)[:controller] expect(subject.connected?).to be_falsey end end end describe '#quit' do it 'sends QUIT to the socket, closes the socket and ' + 'returns the socket reply' do subject, socket = default_controller_connect .values_at(:controller, :socket) expect_send_line socket: socket, line: 'QUIT' expected = '250 OK' expect_read_reply socket: socket, returns: expected expect_socket_close socket: socket expect(subject.quit).to eq expected end end describe '#authentication_method' do context 'when first called for the Controller instance' do context 'when method is returned by PROTOCOLINFO socket call' do context 'when method returned is "null"' do it 'returns nil' do subject, socket = expect_authentication_method( socket_call_returns: ['250-AUTH METHODS=NULL', '250 OK']) .values_at(:controller, :socket) expect(subject.authentication_method).to be_nil end end context 'when method returned is not "null"' do it 'returns :the_method_name' do subject, socket = expect_authentication_method( socket_call_returns: ['250-AUTH METHODS=FOO', '250 OK']) .values_at(:controller, :socket) expect(subject.authentication_method).to eq :foo end end end context 'when method is not returned by PROTOCOLINFO socket call' do it 'returns nil' do subject, socket = expect_authentication_method( socket_call_returns: '250 OK') .values_at(:controller, :socket) expect(subject.authentication_method).to be_nil end end it 'ignores any reply lines starting with "250-" but not "250-AUTH METHODS="' do subject, socket = expect_authentication_method( socket_call_returns: ['250-AUTH BAZ=BAR', '250-AUTH METHODS=FOO', '250 OK']) .values_at(:controller, :socket) expect(subject.authentication_method).to eq :foo end end context 'on subsequent calls for the Controller instance' do it 'returns the already instantiated @authentication_method' do subject, socket = expect_authentication_method( socket_call_returns: ['250-AUTH METHODS=FOO', '250 OK']) .values_at(:controller, :socket) expect([subject.authentication_method, subject.authentication_method]) .to eq [:foo, :foo] end end end describe '#authenticate' do context 'when Controller is instantiated with a cookie' do context 'when authenticate call to socket returns "250 OK"' do context 'when #authenticate is called with a cookie' do it 'sends authenticate to the socket with the passed cookie ' + 'and sets @authenticated = true' do instantiated_cookie = 'instantiated_cookie' cookie = 'the_cookie' subject, socket = controller_connect_with_cookie(instantiated_cookie) .values_at(:controller, :socket) expect_send_line socket: socket, line: "AUTHENTICATE \"#{cookie}\"" expect_read_reply socket: socket, returns: '250 OK' subject.authenticate cookie expect(subject.authenticated?).to be_truthy end end context 'when #authenticate is called without a cookie' do it 'sends authenticate to the socket with the controller instantiated cookie ' + 'and sets @authenticated = true' do cookie = 'thecookie' subject, socket = controller_connect_with_cookie(cookie) .values_at(:controller, :socket) expect_send_line socket: socket, line: "AUTHENTICATE \"#{cookie}\"" expect_read_reply socket: socket, returns: '250 OK' subject.authenticate expect(subject.authenticated?).to be_truthy end end end end context 'when authenticate call to socket does not return "250 OK"' do it 'raises AuthenticationError' do subject, socket = default_controller_connect.values_at(:controller, :socket) expect_send_line socket: socket, line: 'AUTHENTICATE' expect_read_reply socket: socket, returns: '251' expect{subject.authenticate} .to raise_error(Controller::AuthenticationError, /251/) end end context 'when Controller is instantiated without a cookie' do it 'sends authenticate to the socket without a cookie' do subject, socket = default_controller_connect.values_at(:controller, :socket) expect_send_line socket: socket, line: 'AUTHENTICATE' expect_read_reply socket: socket, returns: '250 OK' subject.authenticate expect(subject.authenticated?).to be_truthy end end end describe '#authenticated?' do context 'when not authenticated' do it 'is falsey' do subject, socket = default_controller_connect .values_at(:controller, :socket) expect(subject.authenticated?).to be_falsey end end context 'when authenticated' do it 'is truthy' do subject, socket = default_controller_connect .values_at(:controller, :socket) expect_authenticate socket: socket expect(subject.authenticated?).to be_falsey subject.authenticate expect(subject.authenticated?).to be_truthy end end end describe '#version' do context 'when not authenticated' do it 'authenticates, then calls GETINFO to return the version' do the_val = '0.1.2' the_getinfo_call = 'version' subject, socket = default_controller_connect_send_getinfo( getinfo_call: the_getinfo_call, returned_val: the_val).values_at(:controller, :socket) expect(subject.version).to eq the_val end end context 'when authenticated' do it 'calls GETINFO to return the version' do the_val = '0.1.2' the_getinfo_call = 'version' subject, socket = default_controller_connect_send_getinfo( getinfo_call: the_getinfo_call, returned_val: the_val).values_at(:controller, :socket) subject.authenticate expect(subject.version).to eq the_val end end end describe '#config_file' do context 'when not authenticated' do it 'authenticates, then calls GETINFO to return the config-file ' + 'wrapped in a Pathname object' do the_val = '/path/to/config' the_getinfo_call = 'config-file' subject, socket = default_controller_connect_send_getinfo( getinfo_call: the_getinfo_call, returned_val: the_val).values_at(:controller, :socket) subject_config_file = subject.config_file expect(subject_config_file.class.to_s).to eq 'Pathname' expect(subject_config_file.to_s).to eq the_val end end context 'when authenticated' do it 'calls GETINFO to return the config-file wrapped in a Pathname object' do the_val = '/path/to/config' the_getinfo_call = 'config-file' subject, socket = default_controller_connect_send_getinfo( getinfo_call: the_getinfo_call, returned_val: the_val).values_at(:controller, :socket) subject.authenticate subject_config_file = subject.config_file expect(subject_config_file.class.to_s).to eq 'Pathname' expect(subject_config_file.to_s).to eq the_val end end end describe '#config_text' do context 'when not authenticated' do it 'authenticates, then calls GETINFO to return the config-text ' + 'reading each line returned by the socket until a line with a single "."' do the_val = "ControlPort 9051\nRunAsDaemon 1\n" the_getinfo_call = 'config-text' subject, socket = default_controller_connect_send_getinfo( getinfo_call: the_getinfo_call, returned_val: the_val, read_reply_returns: [ '250+config-text=', 'ControlPort 9051', 'RunAsDaemon 1', '.', '250 OK' ]).values_at(:controller, :socket) expect(subject.config_text).to eq the_val end end context 'when authenticated' do it 'calls GETINFO to return the config-text ' + 'reading each line returned by the socket until a line with a single "."' do the_val = "ControlPort 9051\nRunAsDaemon 1\n" the_getinfo_call = 'config-text' subject, socket = default_controller_connect_send_getinfo( getinfo_call: the_getinfo_call, returned_val: the_val, read_reply_returns: [ '250+config-text=', 'ControlPort 9051', 'RunAsDaemon 1', '.', '250 OK' ]).values_at(:controller, :socket) subject.authenticate expect(subject.config_text).to eq the_val end end end describe '#signal' do context 'when not authenticated' do it 'authenticates, then calls SIGNAL and returns the reply' do the_val = 'the reply' the_signal = 'foo' subject, socket = default_controller_connect_send_signal( signal: the_signal, read_reply_returns: the_val).values_at(:controller, :socket) expect(subject.signal(the_signal)).to eq the_val end end context 'when authenticated' do it 'calls SIGNAL and returns the reply' do the_val = 'the reply' the_signal = 'foo' subject, socket = default_controller_connect_send_signal( signal: the_signal, read_reply_returns: the_val).values_at(:controller, :socket) subject.authenticate expect(subject.signal(the_signal)).to eq the_val end end end def default_controller_connect mockSocket = double('socket') allow(TCPSocket).to receive(:new).and_return(mockSocket) allow(mockSocket).to receive(:setsockopt) {controller: Controller.connect, socket: mockSocket} end def controller_connect_with_cookie cookie mockSocket = double('socket') allow(TCPSocket).to receive(:new).and_return(mockSocket) allow(mockSocket).to receive(:setsockopt) {controller: Controller.connect(cookie: cookie), socket: mockSocket} end def close_controller subject allow(subject[:socket]).to receive(:close) subject[:controller].close subject end def expect_send_line p={} expect(p[:socket]).to receive(:write).with("#{p[:line]}\r\n") expect(p[:socket]).to receive(:flush) end def allow_send_line p={} allow(p[:socket]).to receive(:write).with("#{p[:line]}\r\n") allow(p[:socket]).to receive(:flush) end def expect_read_reply p={} expect(p[:socket]).to receive(:readline) .and_return(*p[:returns]) end def allow_read_reply p={} allow(p[:socket]).to receive(:readline) .and_return(*p[:returns]) end def expect_socket_close p={} expect(p[:socket]).to receive(:close) end def expect_authentication_method p={} subject, socket = default_controller_connect .values_at(:controller, :socket) expect_send_line socket: socket, line: 'PROTOCOLINFO' expect_read_reply socket: socket, returns: p[:socket_call_returns] {controller: subject, socket: socket} end def expect_authenticate p={} expect_send_line socket: p[:socket], line: 'AUTHENTICATE' expect_read_reply socket: p[:socket], returns: '250 OK' end def default_controller_connect_send_getinfo p={} subject, socket = default_controller_connect .values_at(:controller, :socket) expect_authenticate socket: socket expect_send_line socket: socket, line: "GETINFO #{p[:getinfo_call]}" expect_read_reply socket: socket, returns: p[:read_reply_returns] || ["#{p[:getinfo_call]}=#{p[:returned_val]}", '250 OK'] {controller: subject, socket: socket} end def default_controller_connect_send_signal p={} subject, socket = default_controller_connect .values_at(:controller, :socket) expect_authenticate socket: socket expect_send_line socket: socket, line: "SIGNAL #{p[:signal]}" expect_read_reply socket: socket, returns: p[:read_reply_returns] {controller: subject, socket: socket} end end end
joshweir/tormanager
lib/tormanager/control.rb
require 'socket' unless defined?(Socket) module Tor ## # Tor Control Protocol (TC) client. # pulled from tor.rb: # https://github.com/dryruby/tor.rb/blob/master/lib/tor/control.rb # because latest version was not pushed to rubygems and needed to bundle into my gem # # The Tor control protocol is used by other programs (such as frontend # user interfaces) to communicate with a locally running Tor process. It # is not part of the Tor onion routing protocol. # # @example Establishing a controller connection (1) # tor = Tor::Controller.new # # @example Establishing a controller connection (2) # tor = Tor::Controller.new(:host => '127.0.0.1', :port => 9051) # # @example Authenticating the controller connection # tor.authenticate # # @example Obtaining information about the Tor process # tor.version #=> "0.2.1.25" # tor.config_file #=> #<Pathname:/opt/local/etc/tor/torrc> # # @see http://gitweb.torproject.org/tor.git?a=blob_plain;hb=HEAD;f=doc/spec/control-spec.txt # @see http://www.thesprawl.org/memdump/?entry=8 # @since 0.1.1 class Controller PROTOCOL_VERSION = 1 ## # @param [Hash{Symbol => Object}] options # @option options [String, #to_s] :host ("127.0.0.1") # @option options [Integer, #to_i] :port (9051) # @option options [String, #to_s] :cookie (nil) # @option options [Integer, #to_i] :version (PROTOCOL_VERSION) def self.connect(options = {}, &block) if block_given? result = block.call(tor = self.new(options)) tor.quit result else self.new(options) end end ## # @param [Hash{Symbol => Object}] options # @option options [String, #to_s] :host ("127.0.0.1") # @option options [Integer, #to_i] :port (9051) # @option options [String, #to_s] :cookie (nil) # @option options [Integer, #to_i] :version (PROTOCOL_VERSION) def initialize(options = {}, &block) @options = options.dup @host = (@options.delete(:host) || '127.0.0.1').to_s @port = (@options.delete(:port) || 9051).to_i @version = (@options.delete(:version) || PROTOCOL_VERSION).to_i connect if block_given? block.call(self) quit end end attr_reader :host, :port ## # Establishes the socket connection to the Tor process. # # @example # tor.close # tor.connect # # @return [void] def connect close @socket = TCPSocket.new(@host, @port) @socket.setsockopt(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE, true) self end ## # Returns `true` if the controller connection is active. # # @example # tor.connected? #=> true # tor.close # tor.connected? #=> false # # @return [Boolean] def connected? !!@socket end ## # Closes the socket connection to the Tor process. # # @example # tor.close # # @return [void] def close @socket.close if @socket @socket = nil self end ## # Tells the Tor process to hang up on this controller connection. # # This command can be used before authenticating. # # @example # C: QUIT # S: 250 closing connection # ^D # # @example # tor.quit # # @return [void] def quit send_line('QUIT') reply = read_reply close reply end ## # Returns information about the authentication method required by the # Tor process. # # This command may be used before authenticating. # # @example # C: PROTOCOLINFO # S: 250-PROTOCOLINFO 1 # S: 250-AUTH METHODS=NULL # S: 250-VERSION Tor="0.2.1.25" # S: 250 OK # # @example # tor.authentication_method #=> nil # tor.authentication_method #=> :hashedpassword # tor.authentication_method #=> :cookie # # @return [Symbol] # @since 0.1.2 def authentication_method @authentication_method ||= begin method = nil send_line('PROTOCOLINFO') loop do # TODO: support for reading multiple authentication methods case reply = read_reply when /^250-AUTH METHODS=(\w*)/ method = $1.strip.downcase.to_sym method = method.eql?(:null) ? nil : method when /^250-/ then next when '250 OK' then break end end method end end ## # Returns `true` if the controller connection has been authenticated. # # @example # tor.authenticated? #=> false # tor.authenticate # tor.authenticated? #=> true # # @return [Boolean] def authenticated? @authenticated || false end ## # Authenticates the controller connection. # # @example # C: AUTHENTICATE # S: 250 OK # # @example # tor.authenticate # # @return [void] # @raise [AuthenticationError] if authentication failed def authenticate(cookie = nil) cookie ||= @options[:cookie] send(:send_line, cookie ? "AUTHENTICATE \"#{cookie}\"" : "AUTHENTICATE") case reply = read_reply when '250 OK' then @authenticated = true else raise AuthenticationError.new(reply) end self end ## # Returns the version number of the Tor process. # # @example # C: GETINFO version # S: 250-version=0.2.1.25 # S: 250 OK # # @example # tor.version #=> "0.2.1.25" # # @return [String] def version send_command(:getinfo, 'version') reply = read_reply.split('=').last read_reply # skip "250 OK" reply end ## # Returns the path to the Tor configuration file. # # @example # C: GETINFO config-file # S: 250-config-file=/opt/local/etc/tor/torrc # S: 250 OK # # @example # tor.config_file #=> #<Pathname:/opt/local/etc/tor/torrc> # # @return [Pathname] def config_file send_command(:getinfo, 'config-file') reply = read_reply.split('=').last read_reply # skip "250 OK" Pathname(reply) end ## # Returns the current (in-memory) Tor configuration. # Response is terminated with a "." # # @example # C: GETINFO config-text # S: 250+config-text= # S: ControlPort 9051 # S: RunAsDaemon 1 # S: . def config_text send_command(:getinfo, 'config-text') reply = "" read_reply # skip "250+config-text=" while line = read_reply break unless line != "." reply.concat(line + "\n") end read_reply # skip "250 OK" return reply end ## # Send a signal to the server # # @example # tor.signal("newnym") # # @return [String] def signal(name) send_command(:signal, name) read_reply end protected ## # Sends a command line over the socket. # # @param [Symbol, #to_s] command # @param [Array<String>] args # @return [void] def send_command(command, *args) authenticate unless authenticated? send_line(["#{command.to_s.upcase}", *args].join(' ')) end ## # Sends a text line over the socket. # # @param [String, #to_s] line # @return [void] def send_line(line) @socket.write(line.to_s + "\r\n") @socket.flush end ## # Reads a reply line from the socket. # # @return [String] def read_reply @socket.readline.chomp end ## # Used to signal an authentication error. # # @see Tor::Controller#authenticate class AuthenticationError < StandardError; end end end
joshweir/tormanager
lib/tormanager/create_eye_config.rb
<reponame>joshweir/tormanager module TorManager class CreateEyeConfig def initialize params={} @settings = params end def create File.open(@settings[:eye_tor_config_path], "w") do |file| file.puts read_eye_tor_config_template_and_substitute_keywords end end private def read_eye_tor_config_template_and_substitute_keywords text = File.read(@settings[:eye_tor_config_template]) eye_tor_config_template_substitution_keywords.each do |keyword| text = text.gsub(/\[\[\[#{keyword}\]\]\]/, @settings[keyword.to_sym].to_s) end text end def eye_tor_config_template_substitution_keywords @settings.keys.map(&:to_s) end end end
joshweir/tormanager
spec/features/process_helper_spec.rb
require "spec_helper" module TorManager describe ProcessHelper do after :all do ProcessHelper.kill_process( ProcessHelper.query_process ['test process','ruby']) end describe ".query_process" do before :all do @pid1 = Process.spawn("ruby -e \"loop{puts 'test process 1'; sleep 5}\"") Process.detach(@pid1) @pid2 = Process.spawn("ruby -e \"loop{puts 'test process 2'; sleep 5}\"") Process.detach(@pid2) @pids = [@pid1, @pid2] end after :all do ProcessHelper.kill_process( ProcessHelper.query_process ['test process','ruby']) end context "param is a string (single query string)" do it "should find processes based on a query string" do expect(ProcessHelper.query_process('test process')) .to include(*@pids) expect(ProcessHelper.query_process('test process 2')) .to include(@pid2) end it "should not find processes that do not exist" do expect(ProcessHelper.query_process('test process a')) .to eq [] end end context "param is an array (multiple query strings)" do it "should find processes based on a query strings" do expect(ProcessHelper.query_process(['test process','ruby','sh'])) .to contain_exactly(*@pids) expect(ProcessHelper.query_process(['test process 2','ruby','sh'])) .to eq([@pid2]) end it "should not find processes that do not exist" do expect(ProcessHelper.query_process(['test process','ruby -i','sh'])) .to eq [] end end end describe ".process_pid_running?" do it "should be true if pid is running" do pid = Process.spawn("ruby -e \"loop{puts 'test process 1'; sleep 5}\"") Process.detach(pid) expect(ProcessHelper.process_pid_running?(pid)) .to be_truthy ProcessHelper.kill_process ProcessHelper.query_process ['ruby', 'test process'] end it "should not be true if pid is not running" do expect(ProcessHelper.process_pid_running?( spawn_and_kill_process_with_intention_that_pid_will_not_be_in_use_after)) .not_to be_truthy end end describe ".kill_process" do context "param is an array (multiple pids)" do it "should kill multiple processes" do pid1 = Process.spawn("ruby -e \"loop{puts 'test process 1'; sleep 5}\"") Process.detach(pid1) pid2 = Process.spawn("ruby -e \"loop{puts 'test process 2'; sleep 5}\"") Process.detach(pid2) pids = [pid1, pid2] expect(ProcessHelper.process_pid_running?(pid1)) .to be_truthy expect(ProcessHelper.process_pid_running?(pid2)) .to be_truthy ProcessHelper.kill_process pids expect(ProcessHelper.process_pid_running?(pid1)) .not_to be_truthy expect(ProcessHelper.process_pid_running?(pid2)) .not_to be_truthy end end context "param is not an array (single pid)" do it "should kill a process" do pid = Process.spawn("ruby -e \"loop{puts 'test process 1'; sleep 5}\"") Process.detach(pid) expect(ProcessHelper.process_pid_running?(pid)) .to be_truthy ProcessHelper.kill_process pid expect(ProcessHelper.process_pid_running?(pid)) .not_to be_truthy end it "should be quiet if the process does not exist upon kill orders" do expect{ProcessHelper.kill_process( spawn_and_kill_process_with_intention_that_pid_will_not_be_in_use_after)} .not_to raise_error end end end describe ".port_is_open?" do it 'should be true if the port is open' do tcp_server_50700 = TCPServer.new('127.0.0.1', 53700) tcp_server_50700.close expect(ProcessHelper.port_is_open?(53700)).to be_truthy end it 'should not be true if the port is not open' do tcp_server_50700 = TCPServer.new('127.0.0.1', 53700) expect(ProcessHelper.port_is_open?(53700)).to_not be_truthy tcp_server_50700.close end end def spawn_and_kill_process_with_intention_that_pid_will_not_be_in_use_after pid = Process.spawn("ruby -e \"loop{puts 'test process'; sleep 5}\"") Process.detach(pid) ProcessHelper.kill_process ProcessHelper.query_process ['ruby', 'test process'] pid end end end
joshweir/tormanager
lib/tormanager/proxy.rb
require 'socksify' module TorManager class Proxy #Socksify::debug = true def initialize params={} @tor_process = params.fetch(:tor_process, nil) end def proxy enable_socks_server yield.tap { disable_socks_server } ensure disable_socks_server end private def enable_socks_server TCPSocket::socks_server = "127.0.0.1" TCPSocket::socks_port = @tor_process.settings[:tor_port] end def disable_socks_server TCPSocket::socks_server = nil TCPSocket::socks_port = nil end end end
joshweir/tormanager
lib/tormanager/ip_address_control.rb
require 'rest-client' module TorManager TorUnavailable = Class.new(StandardError) class IpAddressControl attr_accessor :ip def initialize params={} @tor_process = params.fetch(:tor_process, nil) @tor_proxy = params.fetch(:tor_proxy, nil) @ip = nil @endpoint_change_attempts = 5 end def get_ip ensure_tor_is_available @ip = tor_endpoint_ip end def get_new_ip ensure_tor_is_available get_new_tor_endpoint_ip end private def ensure_tor_is_available raise TorUnavailable, "Cannot proceed, Tor is not running on port " + "#{@tor_process.settings[:tor_port]}" unless TorProcess.tor_running_on? port: @tor_process.settings[:tor_port], parent_pid: @tor_process.settings[:parent_pid] end def tor_endpoint_ip try_getting_endpoint_ip_restart_tor_and_retry_on_fail attempts: 2 rescue Exception => ex puts "Error getting ip: #{ex.to_s}" return nil end def try_getting_endpoint_ip_restart_tor_and_retry_on_fail params={} ip = nil (params[:attempts] || 2).times do |attempt| begin @tor_proxy.proxy do ip = RestClient::Request .execute(method: :get, url: 'http://bot.whatismyipaddress.com') .to_str end break if ip rescue Exception => ex @tor_process.stop @tor_process.start end end ip end def get_new_tor_endpoint_ip @endpoint_change_attempts.times do |i| tor_switch_endpoint new_ip = tor_endpoint_ip if new_ip.to_s.length > 0 && new_ip != @ip @ip = new_ip break end end @ip end def tor_switch_endpoint Tor::Controller.connect(:port => @tor_process.settings[:control_port]) do |tor| tor.authenticate(@tor_process.settings[:control_password]) tor.signal("newnym") sleep 10 end end end end
joshweir/tormanager
spec/spec_helper.rb
<reponame>joshweir/tormanager<gh_stars>1-10 require 'coveralls' Coveralls.wear! require "bundler/setup" require "tormanager" RSpec.configure do |config| # Enable flags like --only-failures and --next-failure config.example_status_persistence_file_path = ".rspec_status" config.expect_with :rspec do |c| c.syntax = :expect end def cleanup_related_files params={} Dir.glob("/tmp/tormanager.tor.#{params[:tor_port]}.*.eye.rb").each{|file| File.delete(file)} Dir.glob("/tmp/tormanager-tor-#{params[:tor_port]}-*.log").each{|file| File.delete(file)} File.delete("/tmp/tormanager.eye.log") if File.exists?("/tmp/tormanager.eye.log") end def read_tor_process_manager_config params={} Dir.glob("/tmp/tormanager.tor.#{params[:tor_port]}.*.eye.rb").each{|file| return File.read(file);} end def tor_process_status params={} EyeManager.status(application: "tormanager-tor-#{params[:tor_port]}-#{params[:parent_pid]}", process: "tor") end def tor_process_listing params={} `ps -ef | grep tor | grep #{params[:tor_port]} | grep #{params[:control_port]}` end end
joshweir/tormanager
spec/features/tor_process_spec.rb
require "spec_helper" module TorManager describe TorProcess do after :all do EyeManager.destroy end context 'when initialized with default params' do before :all do @tp = TorProcess.new end describe "#start" do before :all do EyeManager.destroy cleanup_related_files @tp.settings @in_use_control_port = 50700 @in_use_tor_port = 9250 @tcp_server_50700 = TCPServer.new('127.0.0.1', 50700) @tcp_server_9250 = TCPServer.new('127.0.0.1',9250) end after :all do @tcp_server_50700.close @tcp_server_9250.close EyeManager.destroy end it "validates that the tor control port is open" do expect(@in_use_control_port).to eq 50700 expect(@tcp_server_50700.class).to eq TCPServer expect{TorProcess.new(tor_port: 52700, control_port: @in_use_control_port).start} .to raise_error(/Cannot spawn Tor process as control port 50700 is in use/) end it "validates that the tor port is open" do expect{TorProcess.new(tor_port: @in_use_tor_port, control_port: 53700).start} .to raise_error(/Cannot spawn Tor process as port 9250 is in use/) end context 'when spawning the tor process' do before :all do EyeManager.destroy @tp.start end after :all do @tp.stop end it "creates a tor eye config file for the current Tor instance settings" do expect(read_tor_process_manager_config(@tp.settings)) .to match(/tor --SocksPort #{@tp.settings[:tor_port]}/) end it "starts tor using the hashed_control_password" do expect(tor_process_status(@tp.settings)).to eq "up" expect(tor_process_listing(@tp.settings)) .to match /HashedControlPassword 16:/ end it "does not do any tor logging or eye logging" do expect(File.exists?( "/tmp/tormanager-tor-#{@tp.settings[:tor_port]}-#{@tp.settings[:parent_pid]}.log")) .to be_falsey expect(File.exists?("/tmp/tormanager.eye.log")) .to be_falsey end end end end context 'when initialized with user params' do before :all do @tp = TorProcess.new control_password: '<PASSWORD>', tor_port: 9350, control_port: 53700, tor_logging: true, eye_logging: true, tor_data_dir: '/tmp/tor_data', tor_log_switch: 'notice syslog' end it "should generate a hashed_control_password based on user specified control_password" do expect(@tp.settings[:control_password]).to eq '<PASSWORD>' expect(@tp.settings[:hashed_control_password][0..2]) .to eq '16:' end describe "#start" do after :all do EyeManager.destroy end context 'when spawning the tor process' do before :all do EyeManager.destroy cleanup_related_files @tp.settings @tp.start end after :all do @tp.stop end it "creates a tor eye config file for the current Tor instance settings" do expect(read_tor_process_manager_config(@tp.settings)) .to match(/tor --SocksPort #{@tp.settings[:tor_port]}/) end it "does tor logging when tor_logging is true" do expect(tor_process_status(@tp.settings)).to eq "up" expect(File.exists?( "/tmp/tormanager-tor-#{@tp.settings[:tor_port]}-#{@tp.settings[:parent_pid]}.log")) .to be_truthy end it "does eye logging when eye_logging is true" do expect(File.exists?("/tmp/tormanager.eye.log")) .to be_truthy end it "uses the :tor_data_dir if passed as input" do expect(tor_process_listing(@tp.settings)) .to match /DataDirectory \/tmp\/tor_data\/9350/ end it "uses the :tor_log_switch if passed as input" do expect(tor_process_listing(@tp.settings)) .to match /Log notice syslog/ end end end end describe "#stop" do before :all do @tp = TorProcess.new @tp_keep_config = TorProcess.new dont_remove_tor_config: true, tor_port: 9450, control_port: 53500 cleanup_related_files @tp.settings cleanup_related_files @tp_keep_config.settings end after :all do EyeManager.destroy end it "stops the tor process" do @tp.start expect(tor_process_status(@tp.settings)).to eq "up" @tp.stop expect(tor_process_status(@tp.settings)).to_not match /up|starting/ end it "removes the eye tor config" do expect(File.exists?("/tmp/tormanager.tor.#{@tp.settings[:tor_port]}." + "#{@tp_keep_config.settings[:parent_pid]}.eye.rb")) .to be_falsey end it "leaves the eye tor config if setting :dont_remove_tor_config is true" do @tp_keep_config.start @tp_keep_config.stop expect(File.exists?("/tmp/tormanager.tor.#{@tp_keep_config.settings[:tor_port]}." + "#{@tp_keep_config.settings[:parent_pid]}.eye.rb")) .to be_truthy end end describe ".stop_obsolete_processes" do let(:tpm) { TorProcess.new } before do cleanup_related_files tpm.settings end after do EyeManager.destroy end it "checks if any Tor eye processes " + "are running associated to TorManager instances that no longer exist " + "then issue eye stop orders and kill the eye process as it is stale" do #add dummy process to act as obsolete EyeManager.start config: 'spec/tormanager/eye.test.rb', application: 'tormanager-tor-9450-12345' tpm.start expect(tor_process_status(tpm.settings)).to eq "up" expect(tor_process_status(tor_port: 9450, parent_pid: 12345)).to eq "up" TorProcess.stop_obsolete_processes expect(tor_process_status(tpm.settings)).to eq "up" expect(tor_process_status(tor_port: 9450, parent_pid: 12345)).to_not match /up|starting/ end end describe ".tor_running_on?" do before :all do @tp = TorProcess.new cleanup_related_files @tp.settings end after :all do EyeManager.destroy end it "is true if Tor is running on port" do @tp.start expect(tor_process_status(@tp.settings)).to eq "up" expect(TorProcess.tor_running_on?(port: @tp.settings[:tor_port])) .to be_truthy @tp.stop end it "is not true if Tor is not running on port" do expect(TorProcess.tor_running_on?(port: @tp.settings[:tor_port])) .to be_falsey end it "is true if Tor is running on port and current pid is tor parent_pid" do @tp.start expect(tor_process_status(@tp.settings)).to eq "up" expect(TorProcess.tor_running_on?(port: @tp.settings[:tor_port], parent_pid: @tp.settings[:parent_pid])) .to be_truthy expect(TorProcess.tor_running_on?(port: @tp.settings[:tor_port], parent_pid: @tp.settings[:parent_pid] + 1)) .to be_falsey @tp.stop end end end end
joshweir/tormanager
spec/tormanager/ip_address_control_spec.rb
require "spec_helper" module TorManager describe IpAddressControl do let(:tor_process) { TorManager::TorProcess.new tor_port: 9350, control_port: 53500 } let(:tor_proxy) { Proxy.new tor_process: tor_process } let(:subject) { IpAddressControl.new tor_process: tor_process, tor_proxy: tor_proxy} describe "#get_ip" do it 'raises exception when Tor is unavailable' do raise_exception_when_tor_unavailable_for_method :get_ip end it "makes 2 attempts getting the ip, restarts the TorProcess on retry," + " and returns nil if fails" do allow(TorProcess) .to receive(:tor_running_on?) .with(port: 9350, parent_pid: tor_process.settings[:parent_pid]) .and_return(true) expect(tor_proxy).to receive(:proxy).and_yield.exactly(2).times allow(RestClient::Request) .to receive(:execute) .with(method: :get, url: 'http://bot.whatismyipaddress.com') .and_raise(Exception).exactly(2).times expect(tor_process).to receive(:stop).exactly(2).times expect(tor_process).to receive(:start).exactly(2).times expect(subject.get_ip).to be_nil end it 'uses RestClient to query whatismyipaddress.com to get the ip and returns it' do allow(TorProcess) .to receive(:tor_running_on?) .with(port: 9350, parent_pid: tor_process.settings[:parent_pid]) .and_return(true) expect(tor_proxy).to receive(:proxy).and_yield.exactly(2).times rest_client_request_count = 0 allow(RestClient::Request) .to receive(:execute) .with(method: :get, url: 'http://bot.whatismyipaddress.com') do rest_client_request_count += 1 rest_client_request_count == 1 ? raise(Exception) : '1.2.3.4' end expect(tor_process).to receive(:stop).exactly(1).times expect(tor_process).to receive(:start).exactly(1).times expect(subject.get_ip).to eq '1.2.3.4' end end describe "#get_new_ip" do it 'raises exception when Tor is unavailable' do raise_exception_when_tor_unavailable_for_method :get_new_ip end it "uses TorController to request a new ip address via telnet" do allow(TorProcess) .to receive(:tor_running_on?) .with(port: 9350, parent_pid: tor_process.settings[:parent_pid]) .and_return(true) tor = double("tor") expect(Tor::Controller) .to receive(:connect) .with(:port => 53500).and_yield(tor) expect(tor).to receive(:authenticate).with(tor_process.settings[:control_password]) expect(tor).to receive(:signal).with("newnym") expect(subject).to receive(:sleep) allow(subject).to receive(:tor_endpoint_ip).and_return('5.6.7.8') expect(subject.get_new_ip).to eq '5.6.7.8' expect(subject.ip).to eq '5.6.7.8' end end def raise_exception_when_tor_unavailable_for_method method allow(TorProcess) .to receive(:tor_running_on?) .with(port: 9350, parent_pid: tor_process.settings[:parent_pid]) .and_return(false) expect{subject.send(method)}.to raise_error TorManager::TorUnavailable, /Cannot proceed, Tor is not running on port 9350/ end end end
joshweir/tormanager
lib/tormanager/eye/tor.template.eye.rb
<gh_stars>1-10 require 'eye' if %w(true 1).include?('[[[eye_logging]]]') Eye.config do logger File.join('[[[log_dir]]]', 'tormanager.eye.log') end end Eye.application 'tormanager-tor-[[[tor_port]]]-[[[parent_pid]]]' do stdall File.join('[[[log_dir]]]', 'tormanager-tor-[[[tor_port]]]-[[[parent_pid]]].log') if %w(true 1).include?('[[[tor_logging]]]') trigger :flapping, times: 10, within: 1.minute, retry_in: 10.minutes check :cpu, every: 30.seconds, below: [[[max_tor_cpu_percentage]]], times: 3 check :memory, every: 60.seconds, below: [[[max_tor_memory_usage_mb]]].megabytes, times: 3 process :tor do pid_file File.join('[[[pid_dir]]]', 'tormanager-tor-[[[tor_port]]]-[[[parent_pid]]].pid') start_command "tor --SocksPort [[[tor_port]]] --ControlPort [[[control_port]]] " + "--CookieAuthentication 0 --HashedControlPassword \"[[[hashed_control_password]]]\" --NewCircuitPeriod " + "[[[tor_new_circuit_period]]] " + ('[[[tor_data_dir]]]'.length > 0 ? "--DataDirectory #{File.join('[[[tor_data_dir]]]', '[[[tor_port]]]')} " : "") + ('[[[tor_log_switch]]]'.length > 0 ? "--Log \"[[[tor_log_switch]]]\" " : "") daemonize true end end
joshweir/tormanager
spec/tormanager/process_helper_spec.rb
<gh_stars>1-10 require "spec_helper" module TorManager describe ProcessHelper do describe ".query_process" do context "when param is empty" do it "returns an empty array" do expect(ProcessHelper.query_process(nil)).to eq [] end end context "when param is a string (single query string)" do it "sends ps command to system with query term" do expect(ProcessHelper) .to receive(:`) .with("ps -ef | grep 'test process' | grep -v grep") .and_return("") ProcessHelper.query_process('test process') end it "finds processes based on the query and returns the pids" do allow(ProcessHelper) .to receive(:`) .with("ps -ef | grep 'test process' | grep -v grep") .and_return( "usr 31924 2312 0 Aug14 pts/12 00:00:00 /bin/test process 1\n" + "usr 32021 2312 0 Aug14 pts/13 00:00:00 /usr/bin/test process 2") expect(ProcessHelper.query_process('test process')) .to contain_exactly(31924, 32021) end it "finds a single processes based on the query and returns the pid" do allow(ProcessHelper) .to receive(:`) .with("ps -ef | grep 'test process' | grep -v grep") .and_return( "usr 31924 2312 0 Aug14 pts/12 00:00:00 /bin/test process 1\n") expect(ProcessHelper.query_process('test process')) .to contain_exactly(31924) end end context "when param is an array (multiple query strings)" do it "sends ps command to system with query terms piped" do expect(ProcessHelper) .to receive(:`) .with("ps -ef | grep 'test process' | " + "grep 'ruby' | grep 'sh' | grep -v grep") .and_return("") ProcessHelper.query_process(['test process','ruby','sh']) end end end describe ".process_pid_running?" do it "returns false if pid param is empty" do expect(ProcessHelper.process_pid_running?(nil)).to be_falsey expect(ProcessHelper.process_pid_running?('')).to be_falsey end it "returns false if pid param cannot be coerced into an integer" do allow(Process).to receive(:kill) expect(ProcessHelper.process_pid_running?('1a')).to be_falsey end it "returns true if Kernel.kill does not fail (meaning the process exists)" do expect(Process).to receive(:kill).with(0, 10).exactly(2).times expect(ProcessHelper.process_pid_running?('10')).to be_truthy expect(ProcessHelper.process_pid_running?(10)).to be_truthy end it "returns false if Kernel.kill fails (meaning the process does not exist)" do expect(Process).to receive(:kill).with(0, 10).and_raise(Error).exactly(2).times expect(ProcessHelper.process_pid_running?('10')).to be_falsey expect(ProcessHelper.process_pid_running?(10)).to be_falsey end end describe ".kill_process" do context "when param is an array (multiple pids)" do it 'raises exception if a pid param cannot be coerced into an integer' do allow(ProcessHelper).to receive(:sleep) allow(ProcessHelper).to receive(:process_pid_running?) .with(12345) .and_return(true, true, true, true, true, false) allow(Process).to receive(:kill) expect{ProcessHelper.kill_process([12345, "10a"])}.to raise_error ArgumentError end it 'does not try to kill the process unless it is currently running' do allow(ProcessHelper).to receive(:sleep) allow(ProcessHelper).to receive(:process_pid_running?) .with(12345) .and_return(false) allow(ProcessHelper).to receive(:process_pid_running?) .with(12346) .and_return(false) expect(Process).to_not receive(:kill) ProcessHelper.kill_process [12345, "12346"] end it 'tries to kill using SIGTERM up to 3 attempts, then SIGKILL for 2 more attempts' do allow(ProcessHelper).to receive(:sleep) allow(ProcessHelper).to receive(:process_pid_running?) .with(12345) .and_return(true, true, true, true, true, false) allow(ProcessHelper).to receive(:process_pid_running?) .with(12346) .and_return(true, true, true, false) expect(Process).to receive(:kill).with('TERM', 12345).exactly(3).times expect(Process).to receive(:kill).with('KILL', 12345).exactly(2).times expect(Process).to receive(:kill).with('TERM', 12346).exactly(3).times ProcessHelper.kill_process [12345, "12346"] end it 'raises exception if fails to kill the process' do allow(ProcessHelper).to receive(:sleep) allow(ProcessHelper).to receive(:process_pid_running?) .with(12345) .and_return(true, true, true, true, true, true) expect(Process).to receive(:kill).with('TERM', 12345).exactly(3).times expect(Process).to receive(:kill).with('KILL', 12345).exactly(2).times expect{ProcessHelper.kill_process [12345, "12346"]} .to raise_error TorManager::CannotKillProcess, /Couldnt kill pid: 12345/ end end context "when param is not an array (single pid)" do it "raises exception if a pid param cannot be coerced into an integer" do allow(ProcessHelper).to receive(:sleep) allow(Process).to receive(:kill) expect{ProcessHelper.kill_process "10a"}.to raise_error ArgumentError end it "kills the process much the same as if the param was an array" do allow(ProcessHelper).to receive(:sleep) allow(ProcessHelper).to receive(:process_pid_running?) .with(12345) .and_return(true, true, true, true, true, false) expect(Process).to receive(:kill).with('TERM', 12345).exactly(3).times expect(Process).to receive(:kill).with('KILL', 12345).exactly(2).times ProcessHelper.kill_process "12345" end end end describe ".port_is_open?" do let(:server) { double } it "is true when port is open (a TCPServer starts on said port)" do allow(TCPServer).to receive(:new).with('127.0.0.1', 12345).and_return(server) allow(server).to receive(:close) expect(ProcessHelper.port_is_open?(12345)).to be_truthy end it "is false when port is not open (a TCPServer fails to start on said port)" do allow(TCPServer).to receive(:new).with('127.0.0.1', 12345).and_raise(Errno::EADDRINUSE) expect(ProcessHelper.port_is_open?(12345)).to be_falsey end end end end
joshweir/tormanager
spec/tormanager/proxy_spec.rb
require "spec_helper" module TorManager describe Proxy do let(:tor_process) { TorManager::TorProcess.new tor_port: 9350, control_port: 53500 } let(:subject) { Proxy.new tor_process: tor_process } describe "#proxy" do it 'enables the socks server only for the yielded block' do socks_socket_before = "#{TCPSocket::socks_server}:#{TCPSocket::socks_port}" socks_socket = nil subject.proxy do socks_socket = "#{TCPSocket::socks_server}:#{TCPSocket::socks_port}" end socks_socket_after = "#{TCPSocket::socks_server}:#{TCPSocket::socks_port}" expect(socks_socket_before).to eq ":" expect(socks_socket).to eq "127.0.0.1:9350" expect(socks_socket_after).to eq ":" end end end end
andresamayadiaz/autofactura
autofactura.gemspec
<reponame>andresamayadiaz/autofactura $:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "autofactura/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "autofactura" s.version = Autofactura::VERSION s.authors = ["Fco. <NAME>"] s.email = ["<EMAIL>"] s.homepage = "http://www.andresamayadiaz.com" s.summary = "AutoFactura.com es un servicio de Facturacion Electronica (CFDi) en Mexico." s.description = "Mediante esta Gema podras utilizar y consumir el API de AutoFactura.com de manera sencilla." s.files = Dir["{app,config,db,lib}/**/*"] + ["MIT-LICENSE", "Rakefile", "README.rdoc"] s.test_files = Dir["test/**/*"] s.require_paths = ["lib"] s.add_dependency "rails", ">= 3.2.14" #s.add_development_dependency "sqlite3" s.add_development_dependency "bundler", "~> 1.3" s.add_development_dependency "rake" end
andresamayadiaz/autofactura
test/autofactura_test.rb
require 'test_helper' class AutofacturaTest < ActiveSupport::TestCase test "truth" do assert_kind_of Module, Autofactura end test "comprobante" do comp = create_comprobante() comprobante = Autofactura::Comprobante.new( comp ) #puts "COMPROBANTE: " + comprobante.to_json assert_not_nil(comprobante, "El Comprobante no se ha creado.") end test "emitir_comprobante" do # Comprobante comp = create_comprobante_descuento() comprobante = Autofactura::Comprobante.new( comp ) af = Autofactura::Autofactura.new( { :user => 'XYZ', :sucursal => 'XYZ' } ) resp = af.emitir(comprobante) puts "EMITIR REGRESA" puts "----------------------------" puts resp.to_json puts "----------------------------" puts resp.body puts "----------------------------" end def create_comprobante comp = { :serie => "ABC", :tipoDeComprobante => "ingreso", :condicionesDePago => "CONTADO", :formaDePago => "PAGO EN UNA SOLA EXHIBICION", :metodoDePago => "NO IDENTIFICADO", :numerocta => "NO IDENTIFICADO", :version => "3.2", :tipoCambio => 1, :moneda => "MXN", :decimales => 2, :Receptor => { :rfc => "RFC_RECEPTOR", :nombre => "<NAME>CIAL SA DE CV", :email => "<EMAIL>", :Domicilio => { :noExterior => "103", :calle => "San Juan", :colonia => "Colonia", :municipio => "Monterrey", :estado => "Nuevo Leon", :pais => "Mexico", :codigoPostal => "66250" } # Fin Domicilio }, # Fin Receptor :Conceptos => [{ :cantidad => 1, :unidad => "NO APLICA", :descripcion => "Primer Concepto de Prueba", :valorUnitario => 1, :ret_iva => 0, :tras_ieps => 0, :tras_iva => 16, :ret_isr => 0 },{ :cantidad => 1, :unidad => "NO APLICA", :descripcion => "Segundo Concepto de Prueba", :valorUnitario => 1, :ret_iva => 0, :tras_ieps => 0, :tras_iva => 16, :ret_isr => 0 }], # Fin Conceptos :Addenda => "" } return comp end def create_comprobante_descuento comp = { :serie => "ABC", :tipoDeComprobante => "ingreso", :condicionesDePago => "CONTADO", :formaDePago => "PAGO EN UNA SOLA EXHIBICION", :metodoDePago => "NO IDENTIFICADO", :numerocta => "NO IDENTIFICADO", :version => "3.2", :tipoCambio => 1, :moneda => "MXN", :decimales => 2, :descuento_porcentual => 0, :Receptor => { :rfc => "RFC_RECEPTOR", :nombre => "<NAME>", :email => "<EMAIL>", :Domicilio => { :noExterior => "103", :calle => "San Juan", :colonia => "Colonia", :municipio => "Monterrey", :estado => "Nuevo Leon", :pais => "Mexico", :codigoPostal => "66250" } # Fin Domicilio }, # Fin Receptor :Conceptos => [{ :cantidad => 1, :unidad => "NO APLICA", :descripcion => "Primer Concepto de Prueba", :valorUnitario => 10, :ret_iva => 0, :tras_ieps => 0, :tras_iva => 16, :ret_isr => 0 },{ :cantidad => 1, :unidad => "NO APLICA", :descripcion => "Segundo Concepto de Prueba", :valorUnitario => 100, :ret_iva => 0, :tras_ieps => 0, :tras_iva => 16, :ret_isr => 0 }], # Fin Conceptos :Addenda => "" } return comp end end
andresamayadiaz/autofactura
lib/autofactura.rb
require "uri" require "net/http" require "date" module Autofactura # Clase Principal Autofactura class Autofactura attr_accessor :url, :user, :sucursal # Initialize def initialize(params) self.url = params[:url].blank? ? "http://app.autofactura.com/users/api/" : params[:url] self.user = params[:user].blank? ? "" : params[:user] self.sucursal = params[:sucursal].blank? ? "" : params[:sucursal] end # Emite un Comprobatnte CFDi de AutoFactura.com # -------------------------------------------------------------------------------- # -------------------------------------------------------------------------------- def emitir(comprobante) return if invalid? # TODO params = { 'data[metodo]' => 'emitir', 'data[userg]' => self.user, 'data[sucursalg]' => self.sucursal, 'data[Comprobante]' => comprobante.to_json, } request = Net::HTTP.post_form(URI.parse(self.url), params) return request end # Termina Metodo Ticket # Emite un ticket de Autofacturacion # -------------------------------------------------------------------------------- # exito = 1 = Éxito, 0 = Fracaso # mensaje = Mensaje en caso de haber error #Id = Identificador interno de AutoFactura # codigof = Código utilizado por sus clientes para auto facturarse en la aplicación # -------------------------------------------------------------------------------- def ticket(nota) return if invalid? # TODO params = { 'data[metodo]' => 'ticket', 'data[userg]' => self.user, 'data[sucursalg]' => self.sucursal, 'data[nota]' => nota.to_json, } request = Net::HTTP.post_form(URI.parse(self.url), params) return request end # Termina Metodo Ticket # Devuelve un Array de Series con id y nombre # -------------------------------------------------------------------------------- def series return if invalid? params = { 'data[metodo]' => 'series', 'data[userg]' => self.user, 'data[sucursalg]' => self.sucursal } request = Net::HTTP.post_form(URI.parse(self.url), params) #puts request.body series = Array.new if request.kind_of? Net::HTTPSuccess JSON.parse(request.body.to_s).each do |serie| series.push Serie.new({:id => serie['id'], :nombre => serie['nombre']}) end end return series end # Termina Metodo series # Cancela un Comprobante CFDi Emitido # -------------------------------------------------------------------------------- # exito = 1 = Éxito, 0 = Fracaso # mensaje = Mensaje en caso de haber error # fechacancelacion = Fecha de cancelación reportada al SAT formato YYYY-mm- ddTHH:ii:ss # url = URL de descarga de acuse en formato XML # -------------------------------------------------------------------------------- def cancelar(comprobante_uuid) return if invalid? params = { 'data[metodo]' => 'cancelar', 'data[userg]' => self.user, 'data[sucursalg]' => self.sucursal, 'data[id]' => comprobante_uuid } request = Net::HTTP.post_form(URI.parse(self.url), params) #puts request.body return JSON.parse(request.body.to_s) end # Termina Metodo cancelar # Privado private def invalid? self.user.blank? || self.sucursal.blank? || self.url.blank? end end # Termina Clase Autofactura # Clase Serie class Serie attr_accessor :id, :nombre def initialize(params) self.id = params[:id] self.nombre = params[:nombre] end end # Termina Clase Serie # Clase Comprobante class Comprobante attr_accessor :fecha, :serie, :tipoDeComprobante, :condicionesDePago, :formaDePago, :metodoDePago, :numerocta, :version, :tipoCambio, :moneda, :decimales, :Receptor, :Conceptos, :Impuestos, :ret_iva_cant, :tras_ieps_cant, :tras_iva_cant, :ret_isr_cant, :Addenda, :subTotal, :total, :descuento, :descuento_porcentual def initialize(params) # Generales self.fecha = DateTime.parse(Time.now.to_s).strftime("%Y-%m-%dT%H:%M:%S").to_s self.serie = params[:serie] self.tipoDeComprobante = params[:tipoDeComprobante] self.condicionesDePago = params[:condicionesDePago].blank? ? "CONTADO" : params[:condicionesDePago] self.formaDePago = params[:formaDePago].blank? ? "PAGO EN UNA SOLA EXHIBICION" : params[:formaDePago] self.metodoDePago = params[:metodoDePago].blank? ? "NO IDENTIFICADO" : params[:metodoDePago] self.numerocta = params[:numerocta].blank? ? "NO IDENTIFICADO" : params[:numerocta] self.version = params[:version].blank? ? "3.2" : params[:version] self.decimales = params[:decimales].blank? ? 3 : params[:decimales].to_i self.tipoCambio = params[:tipoCambio].blank? ? 1.000 : params[:tipoCambio].to_f.round(self.decimales) self.moneda = params[:moneda].blank? ? "MXN" : params[:moneda] self.descuento_porcentual = params[:descuento_porcentual].blank? ? 0.000 : params[:descuento_porcentual].to_f.round(self.decimales) # Receptor self.Receptor = Receptor.new(params[:Receptor]) # Conceptos e Impuestos # Impuestos por Concepto self.subTotal = 0.000 # subTotal self.Impuestos = Array.new self.Conceptos = Array.new #puts "------- CONCEPTOS -------" params[:Conceptos].each do |conc| imp = {} conc[:descuento_porcentual] = self.descuento_porcentual conc[:decimales] = self.decimales concepto = Concepto.new(conc) unless concepto.tras_iva.blank? imp[:tras_iva] = concepto.tras_iva.to_f.round(self.decimales) imp[:tras_iva_cant] = ( ( concepto.importe - concepto.descuento ) * concepto.tras_iva / 100 ).round(self.decimales) end unless concepto.tras_ieps.blank? imp[:tras_ieps] = concepto.tras_ieps.to_f.round(self.decimales) imp[:tras_ieps_cant] = ( ( concepto.importe - concepto.descuento ) * concepto.tras_ieps / 100 ).round(self.decimales) end unless concepto.ret_iva.blank? imp[:ret_iva] = concepto.ret_iva.to_f.round(self.decimales) imp[:ret_iva_cant] = ( ( concepto.importe - concepto.descuento ) * concepto.ret_iva / 100 ).round(self.decimales) end unless concepto.ret_isr.blank? imp[:ret_isr] = concepto.ret_isr.to_f.round(self.decimales) imp[:ret_isr_cant] = ( ( concepto.importe - concepto.descuento ) * concepto.ret_isr / 100 ).round(self.decimales) end self.Conceptos.push(concepto) self.Impuestos.push(Impuesto.new(imp)) self.subTotal += ( concepto.importe ) end #puts "------- FIN CONCEPTOS -------" # Impuestos Totalizados self.tras_iva_cant = 0.00 self.tras_ieps_cant = 0.00 self.ret_iva_cant = 0.00 self.ret_isr_cant = 0.00 #puts "------- IMPUESTOS -------" self.Impuestos.each do |impuesto| unless impuesto.tras_iva_cant.blank? self.tras_iva_cant += impuesto.tras_iva_cant.to_f.round(self.decimales) end unless impuesto.tras_ieps_cant.blank? self.tras_ieps_cant += impuesto.tras_ieps_cant.to_f.round(self.decimales) end unless impuesto.ret_iva_cant.blank? self.ret_iva_cant += impuesto.ret_iva_cant.to_f.round(self.decimales) end unless impuesto.ret_isr_cant.blank? self.ret_isr_cant += impuesto.ret_isr_cant.to_f.round(self.decimales) end end #puts "------- FIN IMPUESTOS -------" # Totales self.descuento = ( (self.subTotal * self.descuento_porcentual) / 100 ).to_f.round(self.decimales) self.total = ( self.subTotal - self.descuento + self.tras_iva_cant + self.tras_ieps_cant - self.ret_iva_cant - self.ret_isr_cant ).to_f.round(self.decimales) end end # Termina Clase Comprobante # Clase Receptor class Receptor attr_accessor :rfc, :nombre, :email, :Domicilio def initialize(params) self.rfc = params[:rfc] self.nombre = params[:nombre] self.email = params[:email] self.Domicilio = Domicilio.new(params[:Domicilio]) # Clase Domicilio end end # Termina Clase Receptor # Clase Domicilio class Domicilio attr_accessor :noExterior, :noInterior, :calle, :colonia, :municipio, :estado, :pais, :codigoPostal, :referencia def initialize(params) self.noExterior = params[:noExterior] self.noInterior = params[:noInterior].blank? ? nil : params[:noInterior] self.calle = params[:calle] self.colonia = params[:colonia] self.municipio = params[:municipio] self.estado = params[:estado] self.pais = params[:pais] self.codigoPostal = params[:codigoPostal] self.referencia = params[:referencia].blank? ? nil : params[:referencia] end end # Termina Clase Domicilio # Clase Concepto class Concepto attr_accessor :cantidad, :unidad, :descripcion, :valorUnitario, :importe, :tras_iva, :ret_iva, :ret_isr, :tras_ieps, :tras_ieps_cant, :tras_iva_cant, :ret_iva_cant, :ret_isr_cant, :descuento, :descuento_porcentual, :decimales def initialize(params) self.decimales = params[:decimales].blank? ? 3 : params[:decimales].to_i # Generales self.cantidad = params[:cantidad] self.unidad = params[:unidad].blank? ? "NO APLICA" : params[:unidad] self.descripcion = params[:descripcion] self.valorUnitario = params[:valorUnitario] # Importe self.importe = (self.cantidad * self.valorUnitario).to_f.round(self.decimales) # Descuento self.descuento_porcentual = params[:descuento_porcentual].blank? ? nil : params[:descuento_porcentual].to_f.round(self.decimales) if params[:descuento_porcentual].blank? self.descuento = 0.00 else self.descuento = ( self.importe * self.descuento_porcentual / 100 ).to_f.round(self.decimales) end # Impuestos # Impuestos Porcentaje self.tras_iva = params[:tras_iva].blank? ? 0 : params[:tras_iva].to_f.round(self.decimales) self.ret_iva = params[:ret_iva].blank? ? 0 : params[:ret_iva].to_f.round(self.decimales) self.ret_isr = params[:ret_isr].blank? ? 0 : params[:ret_isr].to_f.round(self.decimales) self.tras_ieps = params[:tras_ieps].blank? ? 0 : params[:tras_ieps].to_f.round(self.decimales) # Impuestos Cantidad self.tras_ieps_cant = ( ( self.importe - self.descuento ) * params[:tras_ieps] / 100 ).to_f.round(self.decimales) self.ret_isr_cant = ( ( self.importe - self.descuento ) * params[:ret_isr] / 100 ).to_f.round(self.decimales) self.ret_iva_cant = ( ( self.importe - self.descuento ) * params[:ret_iva] / 100 ).to_f.round(self.decimales) self.tras_iva_cant = ( ( self.importe - self.descuento ) * params[:tras_iva] / 100 ).to_f.round(self.decimales) end def invalid if self.unidad.blank? raise 'Debe especificar la unidad del concepto.' end if self.cantidad <= 0 raise 'La cantidad del concepto no puede ser 0 o menor.' end return false end end # Termina Clase Concepto # Clase Impuesto class Impuesto attr_accessor :tras_iva, :ret_iva, :ret_isr, :tras_ieps, :tras_ieps_cant, :ret_isr_cant, :ret_iva_cant, :tras_iva_cant def initialize(params) self.tras_iva = params[:tras_iva].blank? ? 0 : params[:tras_iva].to_f self.ret_iva = params[:ret_iva].blank? ? 0 : params[:ret_iva].to_f self.ret_isr = params[:ret_isr].blank? ? 0 : params[:ret_isr].to_f self.tras_ieps = params[:tras_ieps].blank? ? 0 : params[:tras_ieps].to_f self.tras_ieps_cant = params[:tras_ieps_cant].blank? ? 0 : params[:tras_ieps_cant].to_f self.ret_isr_cant = params[:ret_isr_cant].blank? ? 0 : params[:ret_isr_cant].to_f self.ret_iva_cant = params[:ret_iva_cant].blank? ? 0 : params[:ret_iva_cant].to_f self.tras_iva_cant = params[:tras_iva_cant].blank? ? 0 : params[:tras_iva_cant].to_f end end # Termina Clase Impuesto # Clase Remision class Remision attr_accessor :sucursal, :formapago, :metodopago, :moneda, :rate, :descuento, :articulos def initialize(params) self.sucursal = params[:sucursal] self.formapago = params[:formapago].blank? ? "PAGO EN UNA SOLA EXHIBICION" : params[:formapago] self.metodopago = params[:metodopago].blank? ? "CONTADO" : params[:metodopago] self.moneda = params[:moneda].blank? ? "MXN" : params[:moneda] self.rate = params[:rate].blank? ? "1.00" : params[:rate] self.descuento = params[:descuento].blank? ? "0.00" : params[:descuento] self.articulos = params[:articulos] end end # Termina Clase Remision # Clase Nota class Nota attr_accessor :Ingreso, :Articulos, :decimales def initialize(params) self.decimales = params[:decimales].blank? ? 3 : params[:decimales].to_i # TODO Duda Objeto Ingreso ??? #{ # "Ingreso": { # "sucursal": "Matriz", # "formapago": "Tarjeta", # "metodopago": "Tarjeta", # "moneda": "MXN", # "rate": "1.00", # "descuento": "0" # }, # "Articulos": [{ # "nombre": "Renovacion 2014-2015: rekargas.com", # "precios": "900", # "cantidades": "1", # "unidades": "Desarrollo", # "ivatrans": "16", # "iepstrans": "0", # "ivaret": "0", # "isret": "0" # }] #} self.Ingreso = Ingreso.new(params[:Ingreso]) self.Articulos = Array.new params[:Articulos].each do |articulo| articulo[:decimales] = self.decimales art = Articulo.new(articulo) self.Articulos.push(art) end end end # Termina Clase Nota # Clase Ingreso class Ingreso attr_accessor :sucursal, :formapago, :metodopago, :moneda, :rate, :descuento def initialize(params) self.sucursal = params[:sucursal] self.formapago = params[:formaDePago] self.metodopago = params[:metodoDePago] self.moneda = params[:moneda] self.rate = params[:tipoCambio] self.descuento = params[:descuento].blank? ? "0.00" : params[:descuento] end end # Termina Clase Ingreso # Clase Articulo class Articulo attr_accessor :nombre, :precios, :cantidades, :unidades, :ivatrans, :iepstrans, :ivaret, :isret, :decimales def initialize(params) self.decimales = params[:decimales].blank? ? 3 : params[:decimales].to_i self.nombre = params[:nombre] self.precios = params[:precios].to_f.round(self.decimales) self.cantidades = params[:cantidades].to_f.round(self.decimales) self.unidades = params[:unidades].blank? ? "no aplica" : params[:unidades] self.ivatrans = params[:ivatrans].blank? ? "0.00" : params[:ivatrans].to_f.round(self.decimales) self.iepstrans = params[:iepstrans].blank? ? "0.00" : params[:iepstrans].to_f.round(self.decimales) self.ivaret = params[:ivaret].blank? ? "0.00" : params[:ivaret].to_f.round(self.decimales) self.isret = params[:isret].blank? ? "0.00" : params[:isret].to_f.round(self.decimales) end end # Termina Clase Articulo end
JackSullivan/databasedotcom
lib/databasedotcom/sobject.rb
<filename>lib/databasedotcom/sobject.rb require 'databasedotcom/sobject/sobject' require 'databasedotcom/sobject/aggregate_result'
JackSullivan/databasedotcom
spec/lib/sobject/sobject_spec.rb
<reponame>JackSullivan/databasedotcom<filename>spec/lib/sobject/sobject_spec.rb require 'rspec' require 'spec_helper' require 'databasedotcom' describe Databasedotcom::Sobject::Sobject do class TestClass < Databasedotcom::Sobject::Sobject end before do @client = Databasedotcom::Client.new(File.join(File.dirname(__FILE__), "../../fixtures/databasedotcom.yml")) @client.authenticate(:token => "<PASSWORD>", :instance_url => "https://na9.salesforce.com") TestClass.client = @client end describe "materialization" do context "with a valid Sobject name" do response = JSON.parse(File.read(File.join(File.dirname(__FILE__), "../../fixtures/sobject/sobject_describe_success_response.json"))) it "requests a description of the class" do @client.should_receive(:describe_sobject).with("TestClass").and_return(response) TestClass.materialize("TestClass") end context "with a response" do before do @client.stub(:describe_sobject).and_return(response) TestClass.materialize("TestClass") @sobject = TestClass.new end describe ".attributes" do it "returns the attributes for this Sobject" do TestClass.attributes.should_not be_nil TestClass.attributes.should =~ response["fields"].collect { |f| [f["name"], f["relationshipName"]] }.flatten.compact end end describe "getters and setters" do response["fields"].collect { |f| f["name"] }.each do |name| it "creates a getter and setter for the #{name} attribute" do @sobject.should respond_to(name.to_sym) @sobject.should respond_to("#{name}=".to_sym) end end end describe "default values" do response["fields"].each do |f| it "sets #{f['name']} to #{f['defaultValueFormula'] ? f['defaultValueFormula'] : 'nil'}" do @sobject.send(f["name"].to_sym).should == f["defaultValueFormula"] end end end end end context "with an invalid Sobject name" do it "propagates exceptions" do @client.should_receive(:describe_sobject).with("TestClass").and_raise(Databasedotcom::SalesForceError.new(double("result", :body => "{}"))) lambda { TestClass.materialize("TestClass") }.should raise_error(Databasedotcom::SalesForceError) end end end context "with a materialized class" do before do response = JSON.parse(File.read(File.join(File.dirname(__FILE__), "../../fixtures/sobject/sobject_describe_success_response.json"))) @client.should_receive(:describe_sobject).with("TestClass").and_return(response) TestClass.materialize("TestClass") @field_names = TestClass.description["fields"].collect { |f| f["name"] } end describe "#==" do before do @first = TestClass.new("Id" => "foo") end context "when the objects are the same class" do context "when the ids match" do before do @second = TestClass.new("Id" => "foo") end it "returns true" do @first.should == @second end end context "when the ids do not match" do before do @second = TestClass.new("Id" => "bar") end it "returns false" do @first.should_not == @second end end end context "when the objects are different classes" do before do @second = stub(:is_a? => false) end it "returns false" do @first.should_not == @second end end end describe ".new" do it "creates a new in-memory instance with the specified attributes" do obj = TestClass.new("Name" => "foo") obj.Name.should == "foo" obj.should be_new_record end end describe ".create" do it "returns a new instance with the specified attributes" do @client.should_receive(:create).with(TestClass, "moo").and_return("gar") TestClass.create("moo").should == "gar" end end describe ".find" do context "with a valid id" do it "returns the found instance" do @client.should_receive(:find).with(TestClass, "abc").and_return("bar") TestClass.find("abc").should == "bar" end end context "with an invalid id" do it "propagates exceptions" do @client.should_receive(:find).with(TestClass, "abc").and_raise(Databasedotcom::SalesForceError.new(double("result", :body => "{}"))) lambda { TestClass.find("abc") }.should raise_error(Databasedotcom::SalesForceError) end end end describe ".all" do it "returns a paginated enumerable containing all instances" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass").and_return("foo") TestClass.all.should == "foo" end end describe ".query" do it "constructs and submits a SOQL query" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Name = 'foo'").and_return("bar") TestClass.query("Name = 'foo'").should == "bar" end end describe ".delete" do it "deletes a record specified by id" do @client.should_receive(:delete).with("TestClass", "recordId").and_return("deleteResponse") TestClass.delete("recordId").should == "deleteResponse" end end describe ".first" do it "loads the first record" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass ORDER BY Id ASC LIMIT 1").and_return(["foo"]) TestClass.first.should == "foo" end it "optionally includes SOQL conditions" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE conditions ORDER BY Id ASC LIMIT 1").and_return(["foo"]) TestClass.first("conditions").should == "foo" end end describe ".last" do it "loads the last record" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass ORDER BY Id DESC LIMIT 1").and_return(["bar"]) TestClass.last.should == "bar" end it "optionally includes SOQL conditions" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE conditions ORDER BY Id DESC LIMIT 1").and_return(["bar"]) TestClass.last("conditions").should == "bar" end end describe ".count" do it "gets the record count" do @client.should_receive(:query).with("SELECT COUNT() FROM TestClass").and_return(double("collection", :total_size => 42)) TestClass.count.should == 42 end end describe ".coerce_params" do it "coerces boolean attributes" do TestClass.coerce_params("Checkbox_Field" => "1")["Checkbox_Field"].should be_true TestClass.coerce_params("Checkbox_Field" => "0")["Checkbox_Field"].should be_false TestClass.coerce_params("Checkbox_Field" => true)["Checkbox_Field"].should be_true TestClass.coerce_params("Checkbox_Field" => false)["Checkbox_Field"].should be_false end it "coerces currency attributes" do TestClass.coerce_params("Currency_Field" => "123.4")["Currency_Field"].should == 123.4 TestClass.coerce_params("Currency_Field" => 123.4)["Currency_Field"].should == 123.4 end it "coerces percent attributes" do TestClass.coerce_params("Percent_Field" => "123.4")["Percent_Field"].should == 123.4 TestClass.coerce_params("Percent_Field" => 123.4)["Percent_Field"].should == 123.4 end it "coerces date fields" do today = Date.today Date.stub(:today).and_return(today) TestClass.coerce_params("Date_Field" => "2010-04-01")["Date_Field"].should == Date.civil(2010, 4, 1) TestClass.coerce_params("Date_Field" => "bogus")["Date_Field"].should == Date.today end it "coerces datetime fields" do now = DateTime.now DateTime.stub(:now).and_return(now) TestClass.coerce_params("DateTime_Field" => "2010-04-01T12:05:10Z")["DateTime_Field"].to_s.should == DateTime.civil(2010, 4, 1, 12, 5, 10).to_s TestClass.coerce_params("DateTime_Field" => "bogus")["DateTime_Field"].to_s.should == now.to_s end end describe "dynamic finders" do describe "find_by_xxx" do context "with a single attribute" do it "constructs and executes a query matching the dynamic attributes" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Name = 'Richard' LIMIT 1").and_return(["bar"]) TestClass.find_by_Name('Richard').should == "bar" end it "handles boolean values" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE IsDeleted = false LIMIT 1").and_return(["bar"]) TestClass.find_by_IsDeleted(false).should == "bar" end it "handles numeric values" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Number_Field = 23.4 LIMIT 1").and_return(["bar"]) TestClass.find_by_Number_Field(23.4).should == "bar" end it "handles date values" do today = Date.civil(2011, 04, 02) @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Date_Field = 2011-04-02 LIMIT 1").and_return(["bar"]) TestClass.find_by_Date_Field(today).should == "bar" end it "handles datetime values" do now = DateTime.civil(2011, 04, 02, 20, 15, 33) @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE DateTime_Field = 2011-04-02T20:15:33.000+00:00 LIMIT 1").and_return(["bar"]) TestClass.find_by_DateTime_Field(now).should == "bar" end it "handles time values" do now = Time.utc(2011, "apr", 2, 20, 15, 33) offs = now.utc.strftime("%z").insert(-3, ":") @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Time_Field = 2011-04-02T20:15:33.000#{offs} LIMIT 1").and_return(["bar"]) TestClass.find_by_Time_Field(now).should == "bar" end it "escapes special characters" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Name = 'o\\'reilly' LIMIT 1").and_return(["bar"]) TestClass.find_by_Name("o'reilly").should == "bar" end end context "with multiple attributes" do it "constructs and executes a query matching the dynamic attributes" do @client.should_receive(:query) do |query| query.should include("Name = 'Richard'") query.should include("City = 'San Francisco'") query.should include(" LIMIT 1") ["bar"] end TestClass.find_by_Name_and_City('Richard', 'San Francisco').should == "bar" end end end describe "find_all_by_xxx" do context "with a single attribute" do it "constructs and executes a query matching the dynamic attributes" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Name = 'Richard'").and_return(["bar"]) TestClass.find_all_by_Name('Richard').should == ["bar"] end it "handles boolean values" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE IsDeleted = false").and_return(["bar"]) TestClass.find_all_by_IsDeleted(false).should == ["bar"] end it "handles numeric values" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Number_Field = 23.4").and_return(["bar"]) TestClass.find_all_by_Number_Field(23.4).should == ["bar"] end it "handles date values" do today = Date.civil(2011, 04, 02) @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Date_Field = 2011-04-02").and_return(["bar"]) TestClass.find_all_by_Date_Field(today).should == ["bar"] end it "handles datetime values" do now = DateTime.civil(2011, 04, 02, 20, 15, 33) @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE DateTime_Field = 2011-04-02T20:15:33.000+00:00").and_return(["bar"]) TestClass.find_all_by_DateTime_Field(now).should == ["bar"] end it "handles time values" do now = Time.utc(2011, "apr", 2, 20, 15, 33) offs = now.utc.strftime("%z").insert(-3, ":") @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Time_Field = 2011-04-02T20:15:33.000#{offs}").and_return(["bar"]) TestClass.find_all_by_Time_Field(now).should == ["bar"] end it "escapes special characters" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Name = 'o\\'reilly'").and_return(["bar"]) TestClass.find_all_by_Name("o'reilly").should == ["bar"] end end context "with multiple attributes" do it "constructs and executes a query matching the dynamic attributes" do @client.should_receive(:query) do |query| query.should include("Name = 'Richard'") query.should include("City = 'San Francisco'") ["bar"] end TestClass.find_all_by_Name_and_City('Richard', 'San Francisco').should == ["bar"] end end end end describe "dynamic creators" do describe "find_or_create_by_xxx" do context "with a single attribute" do it "searches for a record with the specified attribute and creates it if it doesn't exist" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Name = 'Richard' LIMIT 1").and_return(nil) @client.should_receive(:create).with(TestClass, "Name" => "Richard").and_return("gar") TestClass.find_or_create_by_Name('Richard').should == "gar" end it "handles boolean values" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE IsDeleted = false LIMIT 1").and_return(nil) @client.should_receive(:create).with(TestClass, "IsDeleted" => false).and_return("gar") TestClass.find_or_create_by_IsDeleted(false).should == "gar" end it "handles numeric values" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Number_Field = 23.4 LIMIT 1").and_return(nil) @client.should_receive(:create).with(TestClass, "Number_Field" => 23.4).and_return("gar") TestClass.find_or_create_by_Number_Field(23.4).should == "gar" end it "handles date values" do today = Date.civil(2011, 04, 02) @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Date_Field = 2011-04-02 LIMIT 1").and_return(nil) @client.should_receive(:create).with(TestClass, "Date_Field" => today).and_return("gar") TestClass.find_or_create_by_Date_Field(today).should == "gar" end it "handles datetime values" do now = DateTime.civil(2011, 04, 02, 20, 15, 33) @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE DateTime_Field = 2011-04-02T20:15:33.000+00:00 LIMIT 1").and_return(nil) @client.should_receive(:create).with(TestClass, "DateTime_Field" => now).and_return("gar") TestClass.find_or_create_by_DateTime_Field(now).should == "gar" end it "handles time values" do now = Time.utc(2011, "apr", 2, 20, 15, 33) offs = now.utc.strftime("%z").insert(-3, ":") @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Time_Field = 2011-04-02T20:15:33.000#{offs} LIMIT 1").and_return(nil) @client.should_receive(:create).with(TestClass, "Time_Field" => now).and_return("gar") TestClass.find_or_create_by_Time_Field(now).should == "gar" end it "escapes special characters" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Name = 'o\\'reilly' LIMIT 1").and_return(nil) @client.should_receive(:create).with(TestClass, "Name" => "o'reilly").and_return("gar") TestClass.find_or_create_by_Name("o'reilly").should == "gar" end end context "with multiple attributes" do it "searches for a record with the specified attributes and creates it if it doesn't exist" do @client.should_receive(:query) do |query| query.should include("Name = 'Richard'") query.should include("City = 'San Francisco'") query.should include(" LIMIT 1") nil end @client.should_receive(:create).with(TestClass, {"Name" => "Richard", "City" => "San Francisco"}).and_return("bar") TestClass.find_or_create_by_Name_and_City('Richard', 'San Francisco').should == "bar" end end context "with a hash argument containing additional attributes" do it "finds by the named arguments, but creates by all values in the hash" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Name = 'Richard' LIMIT 1").and_return(nil) @client.should_receive(:create).with(TestClass, "Name" => "Richard", "Email_Field" => "<EMAIL>", "IsDeleted" => false).and_return("gar") TestClass.find_or_create_by_Name("Name" => 'Richard', "Email_Field" => "<EMAIL>", "IsDeleted" => false).should == "gar" end end end end describe "dynamic initializers" do describe "find_or_initialize_by_xxx" do context "with a single attribute" do it "searches for a record with the specified attribute and initializes it if it doesn't exist" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Name = 'Richard' LIMIT 1").and_return(nil) TestClass.find_or_initialize_by_Name('Richard').Name.should == "Richard" end it "handles boolean values" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE IsDeleted = false LIMIT 1").and_return(nil) TestClass.find_or_initialize_by_IsDeleted(false).IsDeleted.should be_false end it "handles numeric values" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Number_Field = 23.4 LIMIT 1").and_return(nil) TestClass.find_or_initialize_by_Number_Field(23.4).Number_Field.should == 23.4 end it "handles date values" do today = Date.civil(2011, 11, 28) @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Date_Field = 2011-11-28 LIMIT 1").and_return(nil) TestClass.find_or_initialize_by_Date_Field(today).Date_Field.should == today end it "handles datetime values" do now = DateTime.civil(2011, 04, 02, 20, 15, 33) @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE DateTime_Field = 2011-04-02T20:15:33.000+00:00 LIMIT 1").and_return(nil) TestClass.find_or_initialize_by_DateTime_Field(now).DateTime_Field.should == now end it "handles time values" do now = Time.utc(2011, "apr", 2, 20, 15, 33) offs = now.utc.strftime("%z").insert(-3, ":") @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE DateTime_Field = 2011-04-02T20:15:33.000#{offs} LIMIT 1").and_return(nil) TestClass.find_or_initialize_by_DateTime_Field(now).DateTime_Field.should == now end it "escapes special characters" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Name = 'o\\'reilly' LIMIT 1").and_return(nil) TestClass.find_or_initialize_by_Name("o'reilly").Name.should == "o'reilly" end end context "with multiple attributes" do it "searches for a record with the specified attributes and initializes it if it doesn't exist" do @client.should_receive(:query) do |select_statement| select_statement.index("SELECT #{@field_names.join(',')} FROM TestClass WHERE").should be_zero select_statement.index("Name = 'Richard'").should_not == -1 select_statement.index("Email_Field = '<EMAIL>'").should_not == -1 select_statement.index("LIMIT 1").should_not == -1 end result = TestClass.find_or_initialize_by_Name_and_Email_Field('Richard', '<EMAIL>') result.Name.should == "Richard" result.Email_Field.should == "<EMAIL>" end end context "with a hash argument containing additional attributes" do it "finds by the named arguments, but initializes by all values in the hash" do @client.should_receive(:query).with("SELECT #{@field_names.join(',')} FROM TestClass WHERE Name = 'Richard' LIMIT 1").and_return(nil) result = TestClass.find_or_initialize_by_Name("Name" => 'Richard', "Email_Field" => "<EMAIL>", "IsDeleted" => false) result.Name.should == "Richard" result.Email_Field.should == "<EMAIL>" result.IsDeleted.should be_false end end end end describe "#attributes" do it "returns a hash representing the object state" do attrs = { "Name" => "<NAME>", "Number_Field" => 42 } obj = TestClass.new(attrs) attrs.keys.each {|attr| obj.attributes[attr].should == attrs[attr]} end end describe "#attributes=" do it "updates the object with the provided attributes" do obj = TestClass.new obj.Name.should be_nil obj.attributes = { "Name" => "foo" } obj.Name.should == "foo" end end describe "#save" do context "with a new object" do before do @obj = TestClass.new @obj.client = @client @obj.Name = "testname" @obj_double = double("object", "Id" => "foo") end it "creates the record remotely with the set attributes" do @client.should_receive(:create).and_return(@obj_double) @obj.save end it "includes only the createable attributes" do @client.should_receive(:create) do |clazz, attrs| attrs.all? {|attr, value| TestClass.createable?(attr).should be_true} @obj_double end @obj.save end it "sets the Id of the newly-persisted object" do @obj.Id.should be_nil @client.should_receive(:create).and_return(@obj_double) @obj.save @obj.Id.should == @obj_double.Id end end context "with an previously-persisted object" do before do @obj = TestClass.new @obj.client = @client @obj.Id = "rid" end it "updates the record with the attributes of the object" do @client.should_receive(:update).and_return("saved updates") @obj.save.should == "saved updates" end it "includes only the updateable attributes" do @client.should_receive(:update) do |clazz, id, attrs| attrs.all? {|attr, value| TestClass.updateable?(attr).should be_true} end @obj.save end end context "with exclusions argument" do before do @obj = TestClass.new @obj.Name = "testname" @obj.OwnerId = "someownerid" @obj_double = double("object", "Id" => "foo") end it "remove any listed fields from the attributes on create" do @client.should_receive(:create) do |clazz, attrs| attrs.include?("Name").should be_false attrs.include?("OwnerId").should be_true @obj_double end @obj.save(:exclusions => ["Name"]) end it "remove any listed fields from the attributes on update" do @obj.Id = "foo" @client.should_receive(:update) do |clazz, id, attrs| attrs.include?("Name").should be_false attrs.include?("OwnerId").should be_true end result = @obj.save(:exclusions => ["Name"]) end end end describe "#update" do it "returns itself with the updated attributes" do obj = TestClass.new obj.Id = "rid" obj.client = @client @client.should_receive(:update).with(TestClass, "rid", {"Name" => "newName"}).and_return(true) obj.update_attributes({"Name" => "newName"}).Name.should == "newName" end end describe "#delete" do it "deletes itself from the database and returns itself" do obj = TestClass.new obj.Id = "rid" obj.client = @client @client.should_receive(:delete).with(TestClass, "rid").and_return("destroyResponse") obj.delete.should == obj end end describe ".search" do it "submits a SOSL query" do @client.should_receive(:search).with("foo").and_return("bar") TestClass.search("foo").should == "bar" end end describe ".upsert" do it "submits an upsert request" do @client.should_receive(:upsert).with("TestClass", "externalField", "foo", "Name" => "Richard").and_return("gar") TestClass.upsert("externalField", "foo", "Name" => "Richard").should == "gar" end end describe ".label_for" do it "returns the label for a named attribute" do TestClass.label_for("Picklist_Field").should == "Picklist Label" end it "raises ArgumentError for unknown attributes" do lambda { TestClass.label_for("Foobar") }.should raise_error(ArgumentError) end end describe ".picklist_values" do it "returns an array of picklist values for an attribute" do TestClass.picklist_values("Picklist_Field").length.should == 3 end it "raises ArgumentError for unknown attributes" do lambda { TestClass.picklist_values("Foobar") }.should raise_error(ArgumentError) end end describe ".field_type" do it "returns the field type for an attribute" do TestClass.field_type("Picklist_Field").should == "picklist" end it "raises ArgumentError for unknown attributes" do lambda { TestClass.field_type("Foobar") }.should raise_error(ArgumentError) end end describe ".updateable?" do it "returns the updateable flag for an attribute" do TestClass.updateable?("Picklist_Field").should be_true TestClass.updateable?("Id").should be_false end it "raises ArgumentError for unknown attributes" do lambda { TestClass.updateable?("Foobar") }.should raise_error(ArgumentError) end end describe ".createable?" do it "returns the createable flag for an attribute" do TestClass.createable?("IsDeleted").should be_false TestClass.createable?("Picklist_Field").should be_true end it "raises ArgumentError for unknown attributes" do lambda { TestClass.createable?("Foobar") }.should raise_error(ArgumentError) end end describe "#[]" do before do @obj = TestClass.new @obj.Id = "rid" @obj.client = @client end it "allows enumerable-like access to attributes" do @obj.Checkbox_Field = "foo" @obj["Checkbox_Field"].should == "foo" end it "returns nil if the attribute does not exist" do @obj["Foobar"].should == nil end end describe "#[]=" do before do @obj = TestClass.new @obj.Id = "rid" @obj.client = @client end it "allows enumerable-like setting of attributes" do @obj["Checkbox_Field"] = "foo" @obj.Checkbox_Field.should == "foo" end it "raises Argument error if attribute does not exist" do lambda { @obj["Foobar"] = "yes" }.should raise_error(ArgumentError) end end describe "form_for compatibility methods" do describe "#persisted?" do it "returns true if the object has an Id" do obj = TestClass.new obj.should_not be_persisted obj.Id = "foo" obj.should be_persisted end end describe "#new_record?" do it "returns true unless the object has an Id" do obj = TestClass.new obj.should be_new_record obj.Id = "foo" obj.should_not be_new_record end end describe "#to_key" do it "returns a unique object key" do TestClass.new.to_key.should_not == TestClass.new.to_key end end describe "#to_param" do it "returns the object Id" do obj = TestClass.new obj.Id = "foo" obj.to_param.should == "foo" end end end describe "#reload" do before do Databasedotcom::Sobject::Sobject.should_receive(:find).with("foo").and_return(double("sobject", :attributes => { "Id" => "foo", "Name" => "James"})) end it "reloads the object" do obj = TestClass.new obj.Id = "foo" obj.reload end it "resets the object attributes" do obj = TestClass.new obj.Id = "foo" obj.Name = "Jerry" obj.reload obj.Id.should == "foo" obj.Name.should == "James" end it "returns self" do obj = TestClass.new obj.Id = "foo" obj.Name = "Jerry" reloaded_obj = obj.reload reloaded_obj.should == obj end end end end
JackSullivan/databasedotcom
lib/databasedotcom/sobject/aggregate_result.rb
<reponame>JackSullivan/databasedotcom module Databasedotcom module Sobject class AggregateResult def initialize(raw_result) @vals = raw_result.inject({}) do |hsh,(k,v)| hsh[k.to_sym] = v hsh end end def method_missing(field, *args) unless @vals.key?(field) raise NoMethodError, "undefined method #{field} for #{self}" else @vals[field] end end end end end
AcnologiatheEnd/MineEstate
backend/app/serializers/house_serializer.rb
class HouseSerializer < ActiveModel::Serializer def initialize(house_object) @house = house_object end def to_serialized_json options = { include: { user: { only: [:id, :username, :state, :country, :session] } }, except: [:updated_at, :created_at], } @house.to_json(options) end end
AcnologiatheEnd/MineEstate
backend/app/controllers/sessions_controller.rb
class SessionsController < ApplicationController def create @user = User.find_by(username: params[:username]) if @user && @user.authenticate(params[:password]) log_in @user allHouses = House.all render json: HouseSerializer.new(allHouses).to_serialized_json end end def destroy log_out status = "good" render json: status.to_json end private def session_params params.require(:user).permit(:username, :password) end end
AcnologiatheEnd/MineEstate
backend/db/migrate/20201108042241_add_user_id_to_houses.rb
class AddUserIdToHouses < ActiveRecord::Migration[6.0] def change add_column :houses, :user_id, :integer end end
AcnologiatheEnd/MineEstate
backend/app/models/house.rb
class House < ApplicationRecord has_many_attached :pictures belongs_to :user end