text
stringlengths
10
2.61M
class Api::V1::CategoriesController < ApplicationController skip_before_action :authorized, only: :index def index @categories = Category.all render json: @categories end end
# encoding: UTF-8 module OmniSearch # Indexes::Base # class Indexes::Base STORAGE_ENGINE = nil def self.build(collection) instance = self.new instance.build_index(collection) end def self.storage_engine self::STORAGE_ENGINE end def build_index(collection) collec...
shared_examples_for 'Metasploit::Model::Architecture seed' do |attributes={}| attributes.assert_valid_keys(:abbreviation, :bits, :endianness, :family, :summary) context_abbreviation = attributes.fetch(:abbreviation) context "with #{context_abbreviation}" do subject do seed end # put in a let ...
class Bishop < Initialposition def move?(x,y) @x = x @y = y differencex = x-@x_c differencey = y-@y_c if differencex.abs == differencey.abs true else false end end end
class Post < ActiveRecord::Base validates_presence_of :name, :message => "- Write your name dickhead" validates_presence_of :title, :message => "- Write a title you cunt" has_many :comments, :dependent => :destroy has_many :tags accepts_nested_attributes_for :tags, :allow_destroy => :true, :reject_if =>...
if rails_version = ENV['RAILS_VERSION'] require 'rubygems' gem "rails", rails_version end require "rails/version" puts "==== Testing with Rails #{Rails::VERSION::STRING} ====" require 'relevance/tarantula' require 'bundler' Bundler.require require 'ostruct' def test_output_dir File.join(File.dirname(__FILE__),...
# frozen_string_literal: true FactoryBot.define do factory :card do account_id { FactoryBot.create(:account).id } card_type { Faker::String.random(10) } number { Faker::Number.number(12) } cvv { Faker::Number.number(3) } pass { Faker::Number.number(4) } end end
FactoryGirl.define do factory :user do name Faker::Name.name email Faker::Internet.email password Faker::Internet.password factory :user_with_comments do transient do comments_count 5 end after(:create) do |user, evaluator| create_list(:comment, evaluator.comments_c...
module ModelUN require "model_un/data" require 'yaml' class << self def convert(string) if string.length <= 3 self.convert_state_abbr(string.upcase) else self.convert_state_name(string.upcase) end end def convert_state_abbr(state_abbr) self.convert_...
class User < ActiveRecord::Base rolify after_create :add_user_role has_one :userprofile,:dependent=>:destroy # rolify :before_add => :before_add_method # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :regis...
class SampleTypesController < ApplicationController before_action :set_sample_type, only: [:show, :edit, :update, :destroy] before_action :authorize_sample_types, only: [:new, :create, :index] # GET /sample_types def index @page = params[:page] @per_page = 10 @sample_types_filtered = params[:q].pr...
describe CompetitionsController, :type => :controller do describe 'GET open' do it 'renders the page' do process :open, method: :get #, params: { project_id: project } get :open expect(response).to be_successful expect(assigns[:projects]).not_to be_nil expect(response).to render_temp...
class CreateTeamMemberships < ActiveRecord::Migration def change create_table :team_memberships, id: false do |t| t.integer :project_id t.integer :user_id t.boolean :owner t.timestamps end add_index :team_memberships, :owner end end
class UserOrders < ActiveRecord::Migration[5.1] def change create_table :orders_users do |t| t.references :user t.references :order end end end
require 'rails_helper' RSpec.describe 'getTaskListsService', type: :service do let!(:user) { create :user } let!(:task_lists) { create_list(:task_list, 3, user: user) } context 'When valid user_id is sent' do let!(:task_params) do { user_id: user.id } end subject { GetTaskListsS...
module BinaryTree class Node attr_accessor :val, :left, :right def initialize(val) @val, @left, @right = val, nil, nil end end symmetric_tree = BinaryTree::Node.new(1) symmetric_tree.left = BinaryTree::Node.new(2) symmetric_tree.right = BinaryTree::Node.new(2) symmetric_tree.left.left ...
class UserMailer < ActionMailer::Base before_filter :set_url default from: "\"ODC Induction\" <tcs.induction@gmail.com>" include Users::AdminsHelper helper :updates def welcome_email(user) @user = user @login_url = @url + '/change_pwd/' + user.first_login_token.to_s mail(to: user.email, subject: '...
class AddTypeToEasyUserWorkingTimeCalendar < ActiveRecord::Migration def self.up EasyUserWorkingTimeCalendar.reset_column_information EasyUserTimeCalendarException.reset_column_information EasyUserTimeCalendarHoliday.reset_column_information if table_exists?(:easy_user_working_time_calendars) ...
class FriendUserSerializer < ActiveModel::Serializer type 'users' attributes :name, :image, :cover, :uid, :provider has_many :badges has_many :causes belongs_to :organization end
module Fog module Compute class Google class GlobalAddresses < Fog::Collection model Fog::Compute::Google::GlobalAddress def all(options = {}) data = service.list_global_addresses(**options).to_h[:items] || [] load(data) end def get(identity) i...
class CreateProfileItemValues < ActiveRecord::Migration[5.0] def change create_table :profile_item_values do |t| t.references :profile_item, foreign_key: true t.references :conversion, foreign_key: true t.references :profile_value_item_type_value, foreign_key: true t.integer :value ...
include ApplicationHelper require 'spec_helper' describe "Static pages" do subject { page } # makes page the default subject of the test example let(:base_title) { 'RoR Sample App' } describe "Home page" do before { visit root_path } it { should have_content('Sample App') } it { should have_title(full_titl...
class ApplicationController < ActionController::API require "bcrypt" require "jwt" require "csv" def authorize_request header = request.headers["Authorization"] header = header.split(" ").last if header begin @decoded = JsonWebToken.decode(header) @current_user = User.find(@decoded[:us...
maintainer "Skystack Limited" maintainer_email "team@skystack.com" license "Apache 2.0" description "Skystack Remote Client affectionately known as Outpost, a cheap and stable way to collect useful data from your server and send it back to base." long_description IO.read(File.join(File.dirname(__FI...
require 'rubygems' require 'mongo' require 'twitter' require './config' class TweetArchiver # Create a instance of TweetArchiver def initialize(tag) db = Mongo::Client.new(CONNECTION_STRING) @tweets = db[COLLECTION_NAME] # create index @tag = tag @tweets_found = 0 end def update pu...
require_relative('while_statement') class ForStatement def initialize(init, cond, step, statement, lineno) @init = init @cond = cond @step = step @statement = statement @lineno = lineno end def code(scope) if @init @init.code(scope)[0] + WhileStatement.new(@cond, @statement, @step,...
class CreateRsvpInvites < ActiveRecord::Migration def self.up create_table :rsvp_invites do |t| t.string :inviteKey t.string :name t.string :friendlyName t.string :email t.integer :attendingCount t.integer :rsvp_event_id t.timestamps end end def self.down dr...
# frozen_string_literal: true # Credit to Harish Shetty # https://stackoverflow.com/a/2315469/5961578 class ActiveRecord::Base def self.all_polymorphic_types(name) @poly_hash ||= {}.tap do |hash| Dir.glob(File.join(Rails.root, "app", "models", "**", "*.rb")).each do |file| klass = File.basename(fil...
# encoding: utf-8 require 'spec_helper' describe "books/my" do let(:user1) {User.create name: "testuser1"} let(:user2) {User.create name: "testuser2"} before do Book.delete_all view.stub(:current_user) {user1} end let(:book) do book = Book.create( image_url: "http://www.rubyinside.com/wp-...
require 'rails_helper' RSpec.describe SubscriptionsController, type: :controller do let!(:question) { create(:question) } let(:user) { create(:user) } describe 'POST #create' do let(:params) { { question_id: question.id, format: :js } } describe 'Authorized user' do before { login(user) } ...
require "minitest/autorun" require_relative "../lib/module9" include Module9 describe Spaceship do before do @ship = Spaceship.new("Serenity") end describe "when asked for a name" do it "must provide one" do @ship.name.must_equal "Serenity" end end end
class Task < ApplicationRecord belongs_to :project, counter_cache: true end
class Assessor::Task include ActiveModel::Model CLUSTER = Settings.assessor.cluster ECS_CLIENT = ContainerManager.instance.ecs_client MAX_TASK_COUNT = 999 MAX_BATCH_SIZE = 99 attr_accessor :element_group attr_accessor :element_group_ids def initialize(element_group_ids:) self.element_group = Ass...
# -*- coding: utf-8 -*- module WideChars def display_width(txt) #buffer_size = (FFI::WideChars.mbstowcs(nil, self, 0) + 1) * FFI::WideChars.find_type(:wchar_t).size wchar_t = FFI::WideChars.find_type(:wchar_t) buffer_size = (txt.size + 1) * wchar_t.size buffer = FFI::Buffer.new(wchar_t, buffer_size) ...
# Code shared between `Mdm::Module::Instance` and `Metasploit::Framework::Module::Instance`. module Metasploit::Model::Module::Instance extend ActiveModel::Naming extend ActiveSupport::Autoload extend ActiveSupport::Concern include Metasploit::Model::Translation autoload :Spec # # CONSTANTS # # {#...
name 'about_city' maintainer 'YOUR_COMPANY_NAME' maintainer_email 'YOUR_EMAIL' license 'All rights reserved' description 'Installs/Configures about_city' long_description IO.read(File.join(File.dirname(__FILE__), 'README.md')) version '0.1.0' depends "rightscale" recipe "about_...
require 'sinatra' require 'resque' require 'job' get '/' do "Jobs currently queued: #{Resque.size(Job.queue)}" end get '/enqueue' do Resque.enqueue(Job) "Job queued successfully." end
class Feed include ActiveModel::Validations include Rails.application.routes.url_helpers validates_presence_of :current_user attr_accessor :current_user def initialize(arg_hash={}) {user: :current_user}.merge!(arg_hash) # current use is default @user = arg_hash[:user] # user who needs the feeds en...
require 'semantic_logger' module GhBbAudit module Github class GithubRepo include SemanticLogger::Loggable def initialize(user_name,repo_name) @user_name = user_name @repo_name = repo_name end def get_all_file_paths return [] if ( !@user_name || !@repo_name ) ...
#!/usr/bin/env ruby ## # author: Jakub Zak # e-mail: jakub.zak@me.com # module: KRAKER::Util::Stopwatch # detail: Measures time between two points in time, mostly used for performance. ## module KRAKER module Util class Stopwatch def start @start = Time.now end def stop ...
class TypusUpdateSchemaTo01Generator < Rails::Generator::Base def manifest record do |m| config_folder = Typus::Configuration.options[:config_folder] Dir["#{Typus.root}/generators/typus_update_schema_to_01/templates/config/*"].each do |f| base = File.basename(f) m.template "config/#...
class ExperiencesController < ApplicationController include ApplicantConcern def create_experiences experience = Experience.create_or_update_experience(@applicant, experience_params) if experience render :json => {experiences: @applicant.experiences.as_json, success: true}, success: true, status: 200...
class ApplicationController < ActionController::API def validate_token if ((Key.find_by password: request.headers["token"]) != nil) true else head :unauthorized end end end
class AnnounceJob < ApplicationJob queue_as :default def perform(google_calendar_reminder_id) GoogleCalendarReminder. find(google_calendar_reminder_id). announce rescue ActiveRecord::RecordNotFound Rails.logger.warn("Could not announce google_calendar_reminder_id #{google_calendar_reminder_id...
require 'kilomeasure' describe 'duct_insulation' do include_examples 'measure', 'duct_insulation' let!(:before_inputs) do { length_of_duct: 50, perimeter_of_duct_cross_section: 5, temperature_inside_duct: 100, temperature_outside_duct: 50, thickness_of_duct_material: 0.25, ...
module WsdlMapper module Deserializers class AttrMapping < Struct.new(:accessor, :name, :type_name) def getter accessor end def setter "#{accessor}=" end def get(obj) obj.send getter end def set(obj, value) obj.send setter, value e...
require 'wsdl_mapper/dom_generation/generator_base' require 'wsdl_mapper/dom/builtin_type' module WsdlMapper module DomGeneration class DefaultClassGenerator < GeneratorBase def generate(ttg, result) modules = get_module_names ttg.name type_file_for ttg.name, result do |f| write_...
class HomeCharacteristicsFilter < Filter def filter(listings) min_bedrooms, max_bedrooms = self.bedrooms.split("-") min_bathrooms, max_bathrooms = self.bathrooms.split("-") min_sq_footage = self.sq_footage listings.where{bedrooms >= min_bedrooms}.where{bedrooms <= max_bedrooms}.where{bathrooms >= min_...
#!/usr/bin/ruby -w def seperator puts '.... seperator line ...... ' end # print without newline print 'Hello Ruby' # with new # print with newline puts 'Hello Ruby' seperator =begin # Here Document # If the terminator is quoted, # the type of quotes determines the type of the line-oriented string literal. # No...
require 'test_helper' require 'inheriting_thing' class InheritingThingTest < ActiveSupport::TestCase def test_soft_delete_with_functionality_inherited_from_parent thing = InheritingThing.create(:name => 'thing') assert_soft_delete_by_field_working_for(thing) thing.delete end end
# # kaproxy::install # package 'haproxy' do version node[:haproxy][:package][:version] if node[:haproxy][:package][:version] end user = node[:haproxy][:service][:user] group = node[:haproxy][:service][:group] group group do not_if { 'root' == group.to_s.downcase } end user user do comment 'created by chef' gi...
#============================================================================== # ** Window_DebugPanel #------------------------------------------------------------------------------ # This window class handles debug information, should not appear unless it's # in debug mode. Calling this will not start a new scene. #...
class ApiConstraints def initialize(options) @version = options[:version] @default = options[:default] end # Checks wheter the default version is required or the Accept header matches def matches?(req) @default || req.headers['Accept'].inluce?("application/vnd.registration-1dv450.v#{@version}") e...
require 'spec_helper' describe Trade::SandboxShipmentsController do login_admin let(:annual_report_upload){ aru = build(:annual_report_upload) aru.save(:validate => false) aru } let(:sandbox_klass){ Trade::SandboxTemplate.ar_klass(annual_report_upload.sandbox.table_name) } before(:each) do...
# encoding: UTF-8 module Decider module Classifier class Anomaly < Bayes # TODO: caching def avg_scores scores_of_all_documents.map_vals do |scores| Math.avg(scores) end end # TODO: caching def stddevs scores_of_all_documents.map_vals do |...
E('clico em comprar --CartPage') do step 'verifico que estou no carrinho --CartPage' cart.click_buy end E('verifico que estou no carrinho --CartPage') do expecting(cart.is_cart, true, 'Verifica que está no carrinho') end E('contrato um serviço adicional de {string} --CartPage') do | service| cart.hire_additi...
#!/usr/bin/env ruby # frozen_string_literal: true require 'minitest/autorun' require 'fileutils' require 'English' require 'shellwords' require 'erb' require 'tempfile' require 'net/http' TEMPLATE = DATA.read UNSETS = %w[ FZF_DEFAULT_COMMAND FZF_DEFAULT_OPTS FZF_TMUX FZF_TMUX_OPTS FZF_CTRL_T_COMMAND FZF_CTRL_T_...
module SmsR module Providers DEFAULT_PROVIDERS = File.dirname(__FILE__) + '/../providers' extend self def provider(provider_name, &block) SmsR.debug "registering #{provider_name}" providers[provider_name] = Provider.new(block) end def providers @providers ||=...
require 'spec_helper' module Alf module Engine describe Compact::Uniq do it 'should work on an empty operand' do expect(Compact::Uniq.new([]).to_a).to eq([]) end it 'should work when no duplicate is present' do rel = [ {:name => "Jones"}, {:name => "Smith"} ...
#!/usr/bin/env ruby # evaluate the contents of a collection's Dublin Core records for QA purposes # run this from command line # all this does is reads through the DC XML you give it, parses out each element, and then lists each unique value assigned to that element in a list that it prints to standard output require...
Dado("a rota da api de criação de token") do @body = CreateToken("password123") end Quando('realizar uma requisição de criação de token utilizando o método POST') do @response = @createToken.post end Então('a API irá retornar o código {int} e o token gerado') do |code| expect(@response.code).to eq(code) expec...
class Show < ActiveRecord::Base has_many :characters has_many :actors, through: :characters belongs_to :network end
class AddUniqueIndexToTradePermits < ActiveRecord::Migration def change add_index "trade_permits", :number, :name => "trade_permits_number_idx", :unique => true end end
module Taobao class TaobaokeReportMember < Model def self.attr_names [:commission_rate, :real_pay_fee, :app_key, :outer_code, :trade_id, :pay_time, :pay_price, :num_iid, :item_title, :item_num, :category_id, :category_name, :shop_title, :commission, :iid, :seller_nick] end attr_names.each do ...
class Ingredient < ActiveRecord::Base has_many :sandwich_ingredients has_many :ingredients, through: :sandwich_ingredients end
class RepairOrder < ActiveRecord::Base has_many :items, dependent: :destroy accepts_nested_attributes_for :items, allow_destroy: true validates :ro_number, uniqueness: true, presence: true self.per_page = 20 def updated_last soonest_date = updated_at items.each do |i| if i.updated_at > ...
class Bup < Formula homepage "https://github.com/bup/bup" head "https://github.com/bup/bup.git" stable do url "https://github.com/bup/bup/archive/0.26.tar.gz" sha256 "8c25551fa723cfe5dcaaa671c5f0964d8caff22b068923df007a13169d8f015c" # Fix compilation on 10.10 patch do url "https://github.c...
class ParkSerializer < ActiveModel::Serializer attributes :id, :name, :votes, :image end
class BondLetterDetail < ActiveRecord::Base belongs_to :bond_letter has_attached_file :document validates_attachment_content_type :document, :content_type => ['application/pdf', /\Aimage\/.*\Z/], :in => 0.megabytes..40.megabytes end
class LossesController < ApplicationController before_action :authenticate_user! before_action :set_loss, only: [:show, :edit, :update, :destroy] def index # @losses = Loss.all respond_to do |format| format.html format.json { render json: LossDatatable.new(params) } end end def sho...
require 'feidee_utils/record/accessors' require 'feidee_utils/record/computed' require 'feidee_utils/record/namespaced' require 'feidee_utils/record/persistent' require 'feidee_utils/record/utils' module FeideeUtils # The implementation here is wired. # The goal is to create a class hierachy similar to ActiveRecor...
class Cart < ApplicationRecord has_many :cart_items has_many :products, through: :cart_items belongs_to :site before_save :validate_item_count def validate_item_count self.item_count = 0 if item_count < 0 end def empty? item_count.zero? end def add_product(product, quantity = 1) quantit...
# Return "yes" or "no" if all letters in a string have more than one occurrence # and they can be rearanged to be next to the same letters. Read full description on [hackerrank](https://hackerrank.com) def happyLadybugs(b) # create a counter variable by reducing the given string into a new hash with each character #...
class AuthController < ApplicationController skip_before_action :authorized, only: [:create] def create user = User.find_by username:params[:username] if user && user.authenticate(params[:password]) token = encode_token({user_id: user.id}) render json: { user: user, jwt...
module ScannerExtensions # Modue declaration module Extensions; end # Use this for autoloading extensions classes module Loader module_function def load_extensions(namespace = ScannerExtensions::Extensions) extensions = {} namespace.constants.each do |extension| item = namespace.co...
require_relative 'db_connection' require 'active_support/inflector' class SQLObject def self.columns query = <<-SQL SELECT * FROM "#{table_name}" SQL #first result in query returns array of string table names tables = DBConnection.execute(query) @columns = tables.first.map(&:to_sym) ...
class MerchantApplication < ActiveRecord::Base validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i validates :merchant_name, :presence => {:message => 'Please fill out your store name.'} validates :email, :presence => {:message => 'Please fill out your email address.'} validates :...
module Returning module Arel module Visitors module PostgreSQL private def visit_Returning_Arel_Nodes_Returning o if o.returnings.empty? "" else " RETURNING #{o.returnings.join(', ')}" end end def visit_Arel_Nodes_UpdateS...
class AnswerTemplate < ApplicationRecord belongs_to :question has_many :answers validates :content, presence: true, length: {in: 6..160} validates :question_id, presence: true end
require "aethyr/core/actions/commands/emotes/emote_action" module Aethyr module Core module Actions module Frown class FrownCommand < Aethyr::Extend::EmoteAction def initialize(actor, **data) super(actor, **data) end def action event = @data ...
module MetaTagsHelper def meta_title content_for?(:meta_title) ? content_for(:meta_title) : "Bellboy | Your own personal hotel congierge in your pocket" end def meta_description content_for?(:meta_description) ? content_for(:meta_description) : "meta_description" end def meta_image meta_image = ...
class User < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable has_one :patient has_one :physician def user_typ...
module SportsDataApi module Nhl class Exception < ::Exception end DIR = File.join(File.dirname(__FILE__), 'nhl') BASE_URL = 'http://api.sportsdatallc.org/nhl-%{access_level}%{version}' DEFAULT_VERSION = 3 SPORT = :nhl autoload :Season, File.join(DIR, 'season') autoload :Game, File.join(DIR, 'game')...
require_relative '../test_helper' class ServerTest < Minitest::Test include TestHelpers def test_it_can_take_in_params_and_return_200_status params = {"identifier" => "test", "rootUrl" => "http://test.com"} post '/sources', params assert_equal 200, last_response.status end def test_it_returns_400...
class VotesController < ApplicationController before_action :set_vote, only: [:show, :edit, :update, :destroy] def new @project = Project.find(params[:project_id]) @councilmen = Councilman.all @vote = Vote.new end def create @project = Project.find(params[:project_id]) params[:vote].each ...
#!/usr/bin/ruby ###################################################################### #Firefox OS Web App Vulnerability Scanner is an application for scanning #possible DOM based XSS, privileged APIs, and local storage vulnerabilities #in HTML5 web application for Firefox OS. This application also provides user #re...
desc 'start interactive console' task :console do require './environment.rb' binding.pry end desc 'dump all full taxonomies (KPCOFGS) to a CSV file' task :dump do end namespace :db do task :migrate do require './environment.rb' DB.create_table :nodes do primary_key :id Integer :parent_id, i...
# Scrapes html from a page or downloads a file from the net. # Command line arguments : "html (or) media" "website_url (or) file_url" "name_of_file_to_save_in" require 'open-uri' require 'nokogiri' case ARGV[0] when "media" puts "Opening" open(ARGV[1]) do |media| file = open(ARGV[2], 'w') puts "Writing" file....
class Utility::ValidUrl attr_reader :url, :body, :secret def initialize(url: nil, body: nil, secret: nil) @url = url @body = body @secret = secret end def ex raise "No secret key provided" if secret.blank? return false if url.blank? return provided_hash.eql? generated_hash en...
# O módulo SetupsController é usado para criar os prazos class SetupsController < ApplicationController before_action :set_setup, only: [:show, :edit, :update, :destroy] before_action :authenticate_user! before_action except: [:index, :show] do not_admin(setups_path) end def initialize super @set...
module VagrantPlugins module Chef class CommandBuilder def initialize(config, client_type, is_windows=false, is_ui_colored=false) @client_type = client_type @config = config @is_windows = is_windows @is_ui_colored = is_ui_colored if client_type != :solo &...
# frozen_string_literal: true class InvalidCategory < StandardError def initialize(crawler = nil, category = nil, valid_categories = []) msg = "Category '#{category}' is invalid for #{crawler}, " \ "valid categories are: #{valid_categories.to_a.join(', ')}" super(msg) end end
module DataMapper::Spec module CollectionHelpers module GroupMethods def self.extended(base) base.class_inheritable_accessor :loaded base.loaded = false end def should_not_be_a_kicker unless loaded it 'should not be a kicker' do @articles.should_not...
#### # # ClockIn # # Recording information to the nearest possible accuracy. # # We are using this to register datetimes when we may not know the actual time. # # If we are recording time there are 3 possibilities. # We are recording a datetime that is today - we keep this faithfully. # We are recording a datetime in t...
#GET request get '/sample-39-how-to-add-a-signature-to-a-document-and-redirect-after-signing-with-groupdocs-widget' do haml :sample39 end #GET request get '/popup' do haml :popup end #POST request post '/sample39/signature_callback' do begin #Get callback request data = JSON.parse(requ...
require 'spec_helper' describe Scrapper do before do StripBuilder.any_instance.stub({ latest: 666, previous: 0 }) end describe :latest do after { subject.latest } context 'should call #scrap with latest strip' do before do subject.should_receive(:scrap).with(666) { scrap_res...
module Fasterer class ParseError < StandardError attr_reader :file_path def initialize(file_path) @file_path = file_path super("Unable to read #{file_path}") end end end
require 'bettybot/ability' require 'mechanize' module Bettybot::Abilities class Calculator < Bettybot::Ability def process(message) matches = message.text.match /^c (.+)/i if matches agent = Mechanize.new { |agent| agent.user_agent_alias = 'Mac Safari' } agent.get('http://goog...
class FindUserService < BaseService def call(payload) payload_json = JSON.parse(payload) token = payload_json['token'] find_user(token) end private def find_user(token) user = user_by_token(token) if user user_data(user) else unauthorized_data end end def user_da...
require File.join(File.dirname(__FILE__), 'spec_helper') describe "Notes" do before do login(users(:admin)) end describe "creating a note on a GPDB instance" do it "contains the note" do instance = gpdb_instances(:default) visit("#/instances") wait_for_ajax within ".greenplum_i...