text
stringlengths
10
2.61M
class IssueMailer < ApplicationMailer def received issue @issue = issue mail(to: @issue.email, subject: 'Recebemos o seu contato') end end
class DelayedHostelFeeCollectionJob include Notifier def initialize(user,batch,hostel_fee_params) @user=user @batch=batch @params=hostel_fee_params end include I18n include DateFormater def t(obj) I18n.t(obj) end def perform @params.delete("batch_ids") transaction_category = Fina...
class FontStintUltraCondensed < Formula head "https://github.com/google/fonts/raw/main/ofl/stintultracondensed/StintUltraCondensed-Regular.ttf", verified: "github.com/google/fonts/" desc "Stint Ultra Condensed" homepage "https://fonts.google.com/specimen/Stint+Ultra+Condensed" def install (share/"fonts").in...
class InputsController < ApplicationController before_action :set_input, only: [:show] # GET /inputs/new def new @input = Input.new end # GET /inputs/1 # GET /inputs/1.json def show end # POST /inputs # POST /inputs.json def create @input = Input.parse(input_params[:file]) respond_...
class Device < ApplicationRecord has_many :reviews, dependent: :destroy has_attached_file :image, styles: { thumb: ["200x115", :jpg], default: ["225x400", :jpg] }, convert_options: { thumb: "-strip", default: "-strip" }, default_url: ":style/missing.png" validates :name, presence: true validates :...
class BreakConventionTeamSynchronizer < Synchronisable::Synchronizer has_many :players remote_id :maet_id mappings( :eman => :name, :yrtnuoc => :country, :ytic => :city ) except :ignored_1, :ignored_2 gateway TeamGateway end
Pod::Spec.new do |s| s.name = 'ISO8601DateFormatter' s.version = '0.7.2' s.summary = 'A Cocoa NSFormatter subclass to convert dates to and from ISO-8601-formatted strings. Supports calendar, week, and ordinal formats.' s.homepage = 'https://github.com/toto/iso-8601-date-formatter' s....
require 'rubygems' $:.push File.expand_path("../lib", __FILE__) Gem::Specification.new do |s| s.name = 'imlib2-ruby' s.version = '0.5.3' s.date = '2014-04-30' s.summary = 'Imlib2 bindings for Ruby' s.description = 'Image manipulation library' s.authors = ['Paul Duncan...
class Car < ApplicationRecord belongs_to :user has_many :bookings resourcify geocoded_by :full_address # Before seed, comment out: after_validation :geocode # then uncomment and run: $ rake geocode:all CLASS=Car in the terminal # Before seed, comment out: mount_uploader :image, CarImageUploader ...
# frozen_string_literal: true require 'json' require 'resolv' require 'uri' require 'timeout' require 'faraday' require 'faraday_middleware' require 'parallel' module DenshiPaper FUJITSU_DIGITAL_PAPER_SERVICE = 'dp_fujitsu' # TODO: Sony device # SONY_DIGITAL_PAPER_SERVICE = class Discovery def initializ...
require 'net/http' require 'uri' require 'cgi' TWITTER_UPDATE_URL = URI.parse("http://twitter.com/statuses/update.json") namespace :twitter do desc "Update twitter status" task :update do print "Update Twitter Status to (blank for none): " status = $stdin.gets.strip unless status.empty? h...
# frozen_string_literal: true require_relative '../lib/board.rb' describe Board do describe '#make_bottom_row(array)' do subject(:empty_board) { described_class.new } it 'makes an array with a length of 7' do array = Array.new empty_rows = empty_board.make_bottom_row(array) expect(empty_r...
class Stf < ActiveRecord::Base self.table_name = "stf" self.primary_key = "stfid" has_many :luns end
class Pie::Place attr_accessor :description attr_reader :name, :paths def initialize(places, options) @paths = {} @places = places extract_standard_options(options) extract_name_and_description(options) @places[@name] = self end def to_s @name end def path(nodes) ...
require 'test_helper' class AddressesControllerTest < ActionDispatch::IntegrationTest include Devise::Test::IntegrationHelpers setup do @admin = users(:admin) @client = users(:client) end test 'guest does not have access to address' do get addresses_path, xhr: true assert_response :forbidden ...
ActiveAdmin.register MediaGallery do # See permitted parameters documentation: # https://github.com/gregbell/active_admin/blob/master/docs/2-resource-customization.md#setting-up-strong-parameters # permit_params :name, :description, :media_gallery, :id, :media_medias_attributes => [:file, :content_type, :orig...
class UsersController < ApplicationController get "/users/:id" do @user = User.find(params[:id]) if Helpers.is_logged_in?(session) erb :"users/show" else redirect "/login" end end end
require 'ingredient' describe Ingredient do describe '#==' do let(:pomid) {described_class.new(name: 'Tomato', cost: 100)} let(:tomato) {described_class.new(name: 'Tomato', cost: 100)} context 'when ingridients are equal' do it 'they are trule equal' do expect(pomid == tomato).to be true ...
require 'test_helper' class GraphMetaControllerTest < ActionController::TestCase setup do @graph_metum = graph_meta(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:graph_meta) end test "should get new" do get :new assert_response :suc...
describe EOTS do before do EOTS::reset EOTS::email_kind("top_level", header: "Thank you for contacting us.", footer: "We will contact you back as soon as possible.") do EOTS::field("name", "What is your name?", section: :header, columns: 6...
# class CreateUsers < ActiveRecord::Migration # def change # create_table :users, id: :uuid, default: 'uuid_generate_v4()' do |t| # t.string :name # t.string :email # t.string :password_digest # t.timestamps null: false # end # end # end # require 'securerandom' # class CreateProp...
def range(start, final) return [] if final < start [start] + range(start+1, final) end def sum_rec(array) return 0 if array.empty? array.first + sum_rec(array.drop(1)) end def sum_iter(array) array.inject(:+) end def exp1(base,e) return 1 if e == 0 base * exp1(base,e-1) end def exp2(base,e) return 1...
module ProfileCoverImageable extend ActiveSupport::Concern included do mount_uploader :profile_cover_image, ProfileCoverImageUploader mount_base64_uploader :profile_cover_image, ProfileCoverImageUploader, base_filename: :cover_profile_picture # create dinamic methods to handle cropping crop_uploa...
class Author < ActiveRecord::Base validates :name, presence: true validates :email, presence: true, uniqueness: true end
class AddIsAbandonAndVisibleToGoals < ActiveRecord::Migration def change add_column :goals, :is_abandon, :boolean, default: false add_column :goals, :visible, :boolean, default: true end end
module SCC class AverageCalculator def initialize(numbers:) raise ArgumentError if numbers.empty? @numbers = numbers end def call numbers.sum / numbers.size end private attr_reader :numbers end end
class DropGenres < ActiveRecord::Migration[6.1] def change drop_table :genres end end
### Generated by rprotoc. DO NOT EDIT! ### <proto file: fed.proto> # /** # * Copyright 2009 Google 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....
Given(/^I am on the home page$/) do visit root_path end When(/^I click on "([^"]*)"$/) do |target| click_on target end When(/^I fill in as following$/) do |table| table.hashes.each do |row| fill_in row['Field'], with: row['Value'] end end Then(/^I should see "([^"]*)"$/) do |content| expect(page).to ha...
class User < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable before_destroy :must_have_one_admin scope :admin, ...
class ApplicationController < ActionController::Base before_action :configure_permitted_parameters, if: :devise_controller? def after_sign_in_path_for(resource) user_path(current_user) end def after_sign_out_path_for(resource) root_path end def after_inactive_sign_up_path_for(resource) user_path(c...
class ChangeDatatypeForkTypeOfRoadbikes < ActiveRecord::Migration[5.0] def change change_column :roadbikes, :fork_type, :integer end end
require 'spec_helper' describe AngellistApi::Client::Paths, :authenticated, # Personal for authenticated account, manually maintained fixture :vcr => { :cassette_name => 'paths', :record => :none } do let(:client) { AngellistApi::Client.new } context 'when requesting by user IDs' do let(:paths) { client....
class ChangeAvaibleToAvailable < ActiveRecord::Migration def change rename_column :movies, :avaible, :available end end
class ShopsController < ApplicationController def new @shop = Shop.new end def create @shop = current_user.shops.create(shop_params) if @shop redirect_to root_path else render 'new' end end def show @shop = Shop.find(params[:id]) end def edit_store @shop = curr...
module CustomAttrAccessors def attr_accessor_with_history(*names) init_str = '' names.each do |name| name_str = name.to_s at_name_sym = "@#{name_str}".to_sym at_history_sym = "@#{name_str}_history".to_sym init_str += "@#{name_str}_history = []; " define_method("#{name_str...
class StationsController < ApplicationController respond_to :json def index @stations = Station.only(:name, :longitude, :latitude) respond_with @stations end def one @station = Station.find(params[:id]) respond_with @station end end
require 'redis' require 'faker' module FeedStoreHelpers # Creates a Hash in Redis that represents an entry # in the feed. The key is also added to the Redis list # that represents the feed def create_entries(list_name, no_to_create = 1) db = Redis.new no_to_create.times do instagram_id = Faker...
FactoryGirl.define do factory :user do password 12345678 password_confirmation true email { "#{first_name}#{id}@#{last_name}.com" } end end
class PpmController < ApplicationController before_filter :set_default_response_format, :except => [:readme] def readme end def pjlMyTasks id = params[:id] if id path_name = Rails.root.join('app', 'views', 'ppm', 'pjlMyTasks', "#{id}.json") if File.exist? path_name json_data = File.read(path_name) ...
pg_ver = input('pg_version') pg_dba = input('pg_dba') pg_dba_password = input('pg_dba_password') pg_db = input('pg_db') pg_host = input('pg_host') pg_log_dir = input('pg_log_dir') pg_audit_log_dir = input('pg_audit_log_dir') control "V-72923" do title "PostgreSQL must generate audit records when unsuccessful l...
# frozen_string_literal: true module ActiveMerchantSpgateway VERSION = '0.6.3' end
# -*- mode: ruby -*- # vi: set ft=ruby : VAGRANT_ELK_IP = '10.0.3.2' VAGRANT_FE_IP = '10.0.3.3' Vagrant.configure(2) do |config| config.vm.box = "ubuntu1404" config.vm.box_url = "http://cloud-images.ubuntu.com/vagrant/trusty/current/trusty-server-cloudimg-amd64-vagrant-disk1.box" config.vm.provider :virtualbo...
# frozen_string_literal: true class EventAttendeesController < ApplicationController before_action :authenticate_as_owner_or_external! before_action :verify_action_on_player_with_advanced_membership, only: %i[approve] after_action( :log_event, only: %i[approve reject confirm_attendance update_build_growt...
class DiaryController < ApplicationController get '/diary-list' do @notes = Diary.where(user_id: current_user.id).order("created_at DESC") erb :"diaries/index" end end
class AddDefaultValueToMembersLockVersion < ActiveRecord::Migration # railsコマンドでmigrationファイルとひな形を作らせた。 p.284, 285 # rails g migration add_default_value_to_member_lock_version def change # migrate実行中に任意のメッセージを出力できるらしい。 # say 'lock_versionのデフォルト値を0にした。(counter cache機能に対応)' # 中身は手作業で記述 # change_col...
class JobsController < ApplicationController before_action :authenticate_user! def index @jobs = Job.where(user_id: current_user) end def new @user = current_user @job = Job.new end def create @user = User.find(params[:user_id]) @job = Job.new(job_params) @job.user = @user @jo...
# frozen_string_literal: true module GraphQL module Language # @api private # # {GraphQL::Language::DocumentFromSchemaDefinition} is used to convert a {GraphQL::Schema} object # To a {GraphQL::Language::Document} AST node. # # @param context [Hash] # @param only [<#call(member, ctx)>] ...
class CreatePersonnelsPositions < ActiveRecord::Migration[5.0] def change create_table :personnels_positions, id: false do |t| t.belongs_to :personnel, index: true t.belongs_to :position, index: true end end end
require 'rails_helper' describe FizzBuzz do describe '.paginate' do subject { described_class.paginate(1, 10)} it 'returns a lazy enumerator' do expect(subject).to be_instance_of Enumerator::Lazy end it 'returns fizzbuzz from offset to limit' do expect(subject.first.offset).to be 1 ...
#!/usr/bin/env ruby require 'cgi' require 'json' require 'httparty' es_host = ARGV[0] def fetch_kibana_config ( es_host, type, name ) escaped_name = CGI.escape(name) url = "http://#{es_host}/.kibana/#{type}/#{escaped_name}/_source" HTTParty.get url end def erb_to_render_stringified_json( json ) %Q[<%= JSON.p...
require 'test_helper' class MessageTest < ActiveSupport::TestCase def setup @user = users(:tester) @message = @user.messages.build(content: "Test message") end test "message should have a user_id" do @message.user_id = nil assert_not @message.save end end
def letter_count(str) hash_count = Hash.new(0)#creates a new hash with a zero count{"" => 0} any key not entered will have a 0 value auto. str.delete(" ").each_char.sort.map do |letter| #delete the spaces in str, split the letters, sort and map them hash_count[letter] += 1 # where letter will be the new key and...
#!/usr/bin/env ruby # (c) Copyright 2016 Thoughtgang <http://www.thoughtgang.org> # Unit tests for PlanR DataTable datatype require 'test/unit' require 'plan-r/datatype/data_table' # ---------------------------------------------------------------------- class TC_DataTableTest < Test::Unit::TestCase def test_1_ba...
Rails.application.routes.draw do root 'landings#home' get 'landings/help' # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html end
module OrientdbBinary module BaseProtocol class DatasegmentAdd < BinData::Record include OrientdbBinary::BaseProtocol::Base endian :big int8 :operation, value: OrientdbBinary::OperationTypes::REQUEST_DATASEGMENT_ADD int32 :session protocol_string :name protocol_string :loca...
class CreateCategories < ActiveRecord::Migration def change create_table :categories, :id => :uuid do |t| t.string :name t.timestamps end create_table :categorizations, :id => :uuid do |t| t.uuid :category_id t.uuid :todo_id end end end
# frozen_string_literal: true class MovieSerializer include FastJsonapi::ObjectSerializer attribute :purchase_options do |obj| obj.film.purchase_options end attribute :title do |obj| obj.film.title end attribute :plot do |obj| obj.film.plot end end
class Book < ActiveRecord::Base attr_accessible :name, :description has_many :book_tags has_many :tags, :through => :book_tags has_many :author_books has_many :authors, :through => :author_books validates :name, :presence => true validates :description, :presence => true end
class AddUserIdToTweetStats < ActiveRecord::Migration def change add_column :tweet_stats, :user_id, :string end end
require "application_system_test_case" class UnitTypesTest < ApplicationSystemTestCase setup do @unit_type = unit_types(:one) end test "visiting the index" do visit unit_types_url assert_selector "h1", text: "Unit Types" end test "creating a Unit type" do visit unit_types_url click_on "...
json.array! (@scheduled + @topics) do |topic| # json.title topic.title # json.description topic.description # json.scheduled_for topic.scheduled_for # json.meetup_url topic.meetup_url # v- shorthand for -^ json.(topic, :title, :description) json.votes topic.score if topic.scheduled_for ...
require_relative '../lib/sales_engine' class TestCustomerRepository < Minitest::Test def test_it_finds_customers_by_first_name repo = CustomerRepository.new([ { id: 4, first_name: 'Cecilia' }, { id: 2, first_name: 'Dmitry' }, { id: 9, first_name: 'Cecilia' }, ]) # the Cecilias have ids...
# Die Class 1: Numeric # I worked on this challenge [by myself] # I spent [1] hours on this challenge. # 0. Pseudocode # Input: integer for number of sides, .sides, .roll # Output: number of sides, random number betwee 1 and the # of sides # Steps: # create Die class # if sides is less than 1 raise an argument erro...
# frozen_string_literal: true RSpec.describe do resource 'Subscriptions', :stripe do route '/api/v1/subscriptions/', 'Subscriptions endpoint' do post 'Create subscription' do parameter :type, scope: :data, required: true with_options scope: %i[data attributes] do parameter :coupo...
class Picture < ApplicationRecord belongs_to :project mount_uploader :photo, PhotoUploader end
# Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :property do name "My Home" address "6 Wellfield Close" user end end
class Offer < ActiveRecord::Base belongs_to :user belongs_to :shipment, touch: true # => amount: integer validates :amount, presence: true, numericality: { only_integer: true } # => user_id: integer validates :user_id, presence: true validates_associated :user # => shipment_id: integer validates :shi...
$: << '.' # add current path to the search path require 'sinatra/activerecord/rake' require 'app' =begin desc "Reset the data base to initial state" task :clean do sh "mv shortened_urls.db tmp/" sh "mv db/migrate /tmp/" end desc "Create the specific ActiveRecord migration for this app" task :create_migration do sh ...
class Frontier < ApplicationRecord belongs_to :p_name, :foreign_key => [:e_no, :result_no, :generate_no], :primary_key => [:e_no, :result_no, :generate_no], :class_name => 'Name' scope :for_group_select, ->(action_name, params) { select("*"). select("MIN(result_no) AS result_no_min, ...
module Api class MemoriesController < ApplicationController def create @memory = Memory.new(memory_params) return render status: :bad_request if not @memory.save render 'show', status: :ok end private def memory_params params.require(:memory).permit(:event, :date, :pho...
class School < ActiveRecord::Base has_many :houses, through: :schools_houses has_many :schools_houses, class_name: "SchoolsHouses" def self.to_csv attributes = %w{id name distance latitude longitude} CSV.generate(headers: true) do |csv| csv << attributes ...
class ServicesController < ApplicationController def index end def latest_rates if searched? @latest_rates_options = service_params.to_h.symbolize_keys || {} @latest_rates = ExchangerateHost.latest_rates(@latest_rates_options) end set_values([:base, :symbols, :amount]) end def conve...
require 'rspec' require_relative '../lib/ruby_js_html_wrapper/table' require_relative '../lib/ruby_js_html_wrapper/html_document' describe 'Table' do let(:html_table) do arrItems = Array.new hashRow = Hash.new hashRow[:character] = 'Justin Bieber' hashRow[:coolness] = 'not' hashRow[:rating] = 1 ...
class RunsController < ApplicationController before_filter :ensure_run_ownership # GET users/:id/runs # returns all runs connected to current user def index @runs = current_user.runs.most_recent_by_date.page(params[:page]).per(params[:per]) @run_count = @runs.count @user = current_user respond_...
class CauseCategory < ActiveRecord::Base has_many :causes end
# == Schema Information # # Table name: frames # # ball1 :integer # ball2 :integer # ball3 :integer # created_at :datetime not null # game_id :integer # id :integer not null, primary key # lack :integer default(0) # number :integer # previou...
class Tag < ActiveRecord::Base validates :category, presence: true validates :category, uniqueness: true has_and_belongs_to_many :posts end
require 'test/unit' require 'set' require 'yaml' class TestConceptsFrontmatter < Test::Unit::TestCase def test_all_concepts concepts = Dir['_concepts/*'] concepts.each do |file_name| f = YAML.load_file(file_name) f['tabs'].each do |tab| # for each tab, check for the disqus id and disqus...
#pilar de la programacion orientada a objetos #crear clases a partir de otras Clases #padres e hijas #padres de las que se hereda, clase base #clases hijas basadas en las clases base #evita tener que copiar codigo y mejora la performance y el mantenimiento #tendriamos que agregar en todas las clases las variables...
require 'spec_helper' describe ForgotPasswordsController do describe "POST create" do context "with blank email" do it "redirects to new" do post :create, email: "" expect(response).to redirect_to forgot_password_path end it "sets flash[:danger] to blank error message" do ...
require 'level_object/touch_strategy/base' module LevelObject module TouchStrategy module Triangle class Right < TouchStrategy::Base def touch_top(object) object.bottom = wall.geometry.y_at(object.left) object.on_ground = true object.vel_y = 0 object.stand! ...
class Knapsack def initialize(size:) @knapsack_size = size end def pack(items) # Initialize matrix with zeroes. For knapsack of size zero or for zero # elements chosen, first row and column should have zeros. initialize_matrix_for(items.count) # For each item items.each_with_index do |it...
module Elements class ElementBuilder class InvalidProperty < StandardError; end class PropertyNotFound < StandardError; end class DescriptorNotFound < StandardError; end class ParentNotFound < StandardError; end class PropertyBuilder attr_reader :property def initialize(property) ...
# frozen_string_literal: true class Rogare::Commands::Choose extend Rogare::Command command 'choose' usage '`!% <first thing> or <second thing> [or <third thing> and so on]`' handle_help match_command /(.+)/ match_empty :help_message def execute(m, param) xor = /\s+xor\s+/ =~ param if !xor &&...
class CreateRestaurants < ActiveRecord::Migration[6.0] def change create_table :restaurants do |t| t.string :r_name t.text :r_comment t.string :r_address t.references :diary, foreign_key: true, null: false t.timestamps end end end
# 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' }]) # Ch...
class Companies::Admin::JobsController < Admin::BaseController def index @jobs = current_company.jobs end def show @job = Job.find(params[:id]) end def new @job = Job.new end def create @company = Company.friendly.find_by(user_id: current_user.id) @job = @company.jobs.new(job_para...
Then /^I should should see the Manage Users Page$/ do expect(page).to have_content "Unshift.me Users:" end Then /^I should see user records for "(.*?)"$/ do |user_names| user_names.split(",").each do |user_name| within("li.#{user_name}") do page.should have_content(user_name) page.should have_css("...
require 'journey_log' describe JourneyLog do describe '#touch_in' do it 'records an entry_station' do expect(subject.touch_in('Kilburn')).to eq 'Kilburn' end end describe '#touch_out' do it 'creates an entry in journeys' do subject.touch_in('Kilburn') subject.touch_out('Hampstead') ...
class CuisinePreferencesController < ApplicationController skip_before_action :authorized def new cuisine_preference = CuisinePreference.new(cuisine_preference_params) render json: cuisine.to_json(:include => { :cuisines => {:only => [:type]} }) end def index ...
class Talk < Sequel::Model many_to_many :speakers many_to_one :conference many_to_many :playlists self.dataset_module do def sorted order(:title) #change by conference.start_date end end end
class CreateSurveys < ActiveRecord::Migration def change create_table :surveys do |t| t.integer :happy_sad t.integer :lonely_crowded t.integer :horny_pressured t.integer :janitor_nagged t.string :journal_entry t.integer :user_id, index:...
class MessagesController < ApplicationController expose(:messages) expose(:message, attributes: :message_params) def my_messages end def create message.sender_id = current_user.id message.receiver_id = params[:receiver] respond_to do |format| if message.save format.html { redir...
class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable GENDERS = ['Men', 'Women'] devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable has_many :tournaments, for...
require 'test_helper' class MeddlingTargetsControllerTest < ActionDispatch::IntegrationTest setup do @meddling_target = meddling_targets(:one) end test "should get index" do get meddling_targets_url assert_response :success end test "should get new" do get new_meddling_target_url assert...
# == Informacion de la tabla # # Nombre de la tabla: *dbm_estadistica_usuarios* # # id :integer(11) not null, primary key # user_id :integer(11) # total :integer(11) # fecha :date # # Tabla en la que se anotan los usuarios que visitaron en la *fecha* de medicion # a partir de los datos anotados se el...
class RenameMessagesIdColumnToFavorites < ActiveRecord::Migration[5.0] def change rename_column :favorites, :messages_id, :message_id end end
class AddVolcanoToMts < ActiveRecord::Migration def change add_column :mts, :volcano, :boolean end end
class User < ActiveRecord::Base has_one :user_grocery_lists has_many :grocery_lists, through: :user_grocery_lists end