text stringlengths 10 2.61M |
|---|
$:.push File.expand_path("../lib", __FILE__)
# Maintain your gem's version:
require "ar_rollout/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "ar_rollout"
s.version = ArRollout::VERSION
s.authors = ["Enrico Carlesso", "Mattia Gheda", "Mark Punds... |
class ListsController < ApplicationController
before_action :set_list, only: [:show, :edit, :update, :destroy]
before_action :week_jp, only: [:index, :show, :edit]
before_action :Time_Now, only: [:index]
# GET /lists
# GET /lists.json
def index
@user = current_user
@lists = current_user.lists.all.o... |
class Muppet < ActiveRecord::Base
belongs_to :users
def slug
self.name.downcase.gsub(" ", "-") + self.id.to_s
end
def self.find_by_slug(slug)
self.all.find { |muppet| muppet.slug == slug }
end
end
|
module Positionable
extend ActiveSupport::Concern
included do
default_scope -> { order(position: :asc) }
before_save :set_position, if: -> { self.send(:set_position_before_save?) }
end
private
def set_position_before_save?
true
end
def set_position
self.position ||= (self.class.maximu... |
module Jekyll
class SiteUrlGenerator < Generator
def generate(site)
ENV['JEKYLL_ENV'] ||= 'development'
site.config['url'] = site.config["#{ENV['JEKYLL_ENV']}_url"]
end
end
end
|
require 'libraries/git'
describe Git do
def load_resource(resource, *args)
# initialize resource with backend and parameters
@resource_class = Inspec::Resource.registry[resource]
@resource = @resource_class.new(backend, resource, *args)
end
def backend
@backend = Inspec::Backend.create({ backend... |
class Shoes
class EditBox < Element
def initialize(opts = {}, &blk)
opts = opts[:app].basic_attributes opts
#opts = {:height => 100, :width => 100}.update(opts)
opts[:real] = Gtk::TextView.new
opts[:markup] = opts[:text] if opts[:text]
super
@real.signal_connect "clic... |
# frozen_string_literal: true
class ApplicationController < ActionController::Base
add_flash_types :success, :info, :warning, :danger
def line_user?
params['linkToken'].present?
end
def current_user?(user)
current_user == user
end
def set_base_url
@base_url = ENV['BASE_URL']
end
end
|
# Choder - TCP Chat Test Client 2
#
# 20150512 - ThothLogos
#
# Test client for TCP server.
require 'socket'
module ChoderClient
CRLF = "\r\n"
class Client
def initialize(address = "localhost", port = "7680")
@connection = Socket.tcp(address, port)
trap(:TSTP) { exit 130 }
trap(:INT) { ex... |
describe 'our little webserver that could' do
require 'faraday'
before do
@url = "http://localhost:8080"
@response = Faraday.get @url
end
it 'should welcome us to Nginx' do
@response.body.should =~ /Welcome to nginx/
end
it 'should return an OK status code' do
@response.env[:status].shou... |
class Project < ActiveRecord::Base
belongs_to :project
has_many :skills
accepts_nested_attributes_for :skills, allow_destroy: true
def as_json(options = nil)
options.merge!(Project.default_json_options) if options
super(options)
end
def self.default_json_options
{
:include => {
... |
# frozen_string_literal: true
require 'open-uri'
require './lib/models.rb'
require './lib/sticker.rb'
require './lib/definitions.rb'
require './lib/flex_message.rb'
def compose_text_content(msg, mail)
# TODO: convert some codes into LINE emoji
# https://developers.line.me/media/messaging-api/emoji-list.pdf
pa... |
Types::QueryType = GraphQL::ObjectType.define do
name "Query"
# Add root-level fields here.
# They will be entry points for queries on your schema.
# Login Query
# {
# login(email: "john@example.com", password: "12")
# }
field :login, types.String do
argument :email, types.String
argument :pa... |
require 'spec_helper'
# With webmock (fake connections), to check how we handle timeouts.
describe Aptible::Resource::Base do
let(:body) { { 'hello' => '1' } }
let(:json_body) { JSON.unparse(body) }
let(:domain) { 'api.aptible.com' }
subject { Api.new(root: "http://#{domain}") }
context 'with mock connecti... |
class AddProjectBegAndEndDate < ActiveRecord::Migration
def self.up
change_table :projects do |t|
t.rename :proj_date, :proj_beg_date
t.date :proj_end_date
end
end
def self.down
change_table :projects do |t|
t.rename :proj_beg_date, :proj_date
t.remove :proj_end_date
end
end
end
|
module GHI
module Formatting
module Colors
class << self
attr_accessor :colorize
def colorize?
return @colorize if defined? @colorize
@colorize = STDOUT.tty?
end
end
def colorize?
Colors.colorize?
end
def fg color, &block
... |
class Allergy < ApplicationRecord
belongs_to :user
belongs_to :ingredient
validates :user_id, { presence: true, numericality: { only_integer: true } }
validates :ingredient_id, { presence: true, numericality: { only_integer: true } }
end
|
class ConvertTweetsToEvents < ActiveRecord::Migration
class Tweet < ActiveRecord::Base; end
def up
Tweet.find_each do |tweet|
event = Event.find_or_create_by!(
happened_at: tweet.twitter_created_at,
source: :twitter,
external_reference: tweet.twitter_id,
)
event.api_re... |
class AddLeaveDetailsToEmployeePayslips < ActiveRecord::Migration
def self.up
add_column :employee_payslips, :leave_details, :text
end
def self.down
remove_column :employee_payslips, :leave_details
end
end
|
# == Schema Information
#
# Table name: bookings
#
# id :bigint not null, primary key
# arrival_date :date not null
# departure_date :date not null
# num_travelers :integer not null
# hopper_id :integer
# spot_id :integer
# status :str... |
class Photo < ActiveRecord::Base
include Accessable
include Imageable
include Positionable
include Taggable
include PostAttachable
include Likeable
include Commentable
# soft-delete
acts_as_paranoid
attr_accessor :create_image_versions, :slide_thumb_upload, :game_item_image_upload
has_one :ori... |
require 'date'
require 'safe_yaml/load'
SafeYAML::OPTIONS[:suppress_warnings] = true
module Twine
class Plugin
attr_reader :debug, :config
def initialize
@debug = false
require_gems
end
###
# require gems from the yaml config.
#
# gems: [twine-plugin1, twine-2]
#
# ... |
class DestroyDuplicateEvents < ActiveRecord::Migration
def self.up
Sync.all.each do |sync|
User.all.each do |user|
user.apps.each do |app|
events = user.events.of_app(app)
events_to_keep = []
events.each do |event|
previous_event = events_to_keep.last
... |
module Trie
class Encoder
attr :tree
def initialize(tree)
@tree = tree
end
def encode(word)
node = @tree
word.each_char do |char|
node = node.add_child char
end
node.add_child "\n"
end
end
end
|
# frozen_string_literal: true
module Dry
module Logic
class Rule
class Predicate < Rule
def self.specialize(arity, curried, base = Predicate)
super
end
def type
:predicate
end
def name
predicate.name
end
def to_s
... |
xml.instruct! :xml, :version => "1.0"
xml.osm("version" => API_VERSION, "generator" => GENERATOR) do
xml.tag! "user", :id => @user.id,
:display_name => @user.display_name,
:account_created => @user.creation_time.xmlschema do
if @user.description
xml.tag! "description", ... |
class JobsController < ApplicationController
before_action :set_job, only: %i[show edit update destroy]
before_action :authenticate_user!, except: %i[index show]
before_action :correct_user, only: %i[edit update destroy]
# GET /jobs or /jobs.json
def index
@jobs = Job.active.recent_first
end
# GET /... |
class Event
class Email < Event
self.table_name = "email_events"
self.inheritance_column = "inheritance_type"
SENT = "Sent"
OPENED = "Opened"
CLICKED = "Clicked"
TYPES = [SENT, OPENED, CLICKED].freeze
belongs_to :prospect, :touch => true
belongs_to :sent_email
attr_accessible :p... |
class CreateDb < ActiveRecord::Migration
def self.up
create_table "posts", force: true do |t|
t.integer "user_id", null: false
t.text "text", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: ... |
require './RomanNumberGenerator'
require 'test/unit'
class MyTest < Test::Unit::TestCase
def test_number_range
assert(!RomanNumberGenerator.new.convert_number_to_roman(0), 'Argument can not be 0')
assert(!RomanNumberGenerator.new.convert_number_to_roman(-1), 'Argument can not be negative')
assert(!Rom... |
class AddTwoColoumsToShip < ActiveRecord::Migration
def change
add_column :ships, :speed, :string
add_column :ships, :destination, :string
end
end
|
FactoryGirl.define do
factory :image, class: Apress::Images::Image do
title 'Утро в сосновом бору'
comment 'Картина русских художников Ивана Шишкина и Константина Савицкого.'
img { Rack::Test::UploadedFile.new(Rails.root.join('../fixtures/images/sample_image.jpg'), 'image/jpeg') }
position 1
end
... |
ActiveAdmin.register Department do
menu priority: 3, parent: 'Manage'
permit_params :user_id, :name, :phone_number, :unclaimed_response
index do
column :name
column :phone_number
column :unclaimed_user
actions
end
form do |f|
f.inputs do
if resource.persisted?
f.input :user... |
class Reply
attr_accessor :from, :acknowledgedTimestamp, :content
def initialize(from, acknowledgedTimestamp, content)
@from = from
@acknowledgedTimestamp = acknowledgedTimestamp
@content = content
end
end |
class Email
attr_reader :date, :from, :subject
def initialize(subject, headers)
@subject, @date, @from = subject, headers[:date], headers[:from]
end
end
class Mailbox
attr_reader :name, :emails
def initialize(name, emails)
@name, @emails = name, emails
end
end
class MailboxTextFormatter
attr_r... |
# -*- encoding : utf-8 -*-
class PalabrasDatatable
include Rails.application.routes.url_helpers
delegate :content_tag, :params, :h, :link_to, :number_to_currency, :url_helpers, to: :@view
def initialize(view)
@view = view
end
def as_json(options={})
{
sEcho: params[:sEcho].to_i,
iTotalRe... |
# Customise this file, documentation can be found here:
# https://github.com/KrauseFx/fastlane/tree/master/docs
# All available actions: https://github.com/KrauseFx/fastlane/blob/master/docs/Actions.md
# can also be listed using the `fastlane actions` command
# Change the syntax highlighting to Ruby
# All lines starti... |
module Generatable
extend ActiveSupport::Concern
included do
has_many :videos, as: :videoable, dependent: :destroy
end
def video
if videos.loaded?
videos.sort_by(&:id).reject { |v| v.filename.blank? }.last
else
videos.where.not(filename: nil).order(:id).last
end
end
def genera... |
require 'date'
require 'pry'
module Admin
class Reservation
attr_reader :checkin, :checkout, :number_of_rooms
ROOM_COST = 200
def initialize(checkin ,checkout, number_of_rooms)
@checkin = Date.parse(checkin)
@checkout = Date.parse(checkout)
@number_of_rooms = number_of_rooms
... |
class User::NotificationsController < ApplicationController
def index
@notifications = current_user.passive_notifications.paginate(page: params[:page],per_page: 6).order(created_at: :desc)
@notifications.where(checked: false).each do |notification|
notification.update_attributes(checked: true)
end
end
end
|
class Bar
attr_reader :name
attr_accessor :till, :drinks_stock
def initialize(input_name, input_till, input_drinks_stock)
@name = input_name
@till = input_till
@drinks_stock = input_drinks_stock
end
def bar_can_lose_drink(requested_drink)
@drinks_stock.delete(requested_drink)
return @dr... |
require 'rails_helper'
RSpec.describe "Census service" do
context 'GET /api/v1/users' do
xit "can get users from census by name" do
VCR.use_cassette('.census-app') do
name = 'scherer'
url = "/api/v1/users/by_name"
access_token = "#{ENV['census_access_token']}"
census_resul... |
require 'spec_helper'
describe Flickrie::ApiMethods do
it "should upload and delete correctly", :vcr, :cassette => "upload and delete" do
media_id = Flickrie.upload(PHOTO_PATH)
Flickrie.public_media_from_user(USER_NSID).map(&:id).should include(media_id)
Flickrie.delete_media(media_id)
Flickrie.publi... |
class Fulfillment < ActiveRecord::Base
has_paper_trail
acts_as_paranoid
belongs_to :line_item
belongs_to :service
belongs_to :creator, class_name: "Identity"
belongs_to :performer, class_name: "Identity"
has_one :protocol, through: :line_item
has_many :components, as: :composable
has_many :notes, a... |
# Problem 344: Silver dollar game
# http://projecteuler.net/problem=344
# One variant of N.G. de Bruijn's silver dollar game can be described as follows:
#
# On a strip of squares a number of coins are placed, at most one coin per square. Only one coin, called the silver dollar, has any value. Two players take turns ... |
module PaymentGateway
class StripeAdapter
def initialize(api_key = ENV["STRIPE_SECRET_KEY"])
@api_key = api_key
end
def charge(amount, token)
Stripe::Charge.create({
amount: amount,
currency: "eur",
source: token
}, { api_key: @api_key })
rescue Stripe::Inva... |
module Notification::Handles
class Base
def self.find_or_create_notification(event, user)
# Look for corresponding notifications for given object within the last hour
notification = Notification::Notification.where(user_id: user.id, instance_type: event.model_name, instance_id: event.instance.id)
... |
require 'spec_helper'
describe "A summoners" do
before do
@summoner = FactoryGirl.build(:summoner)
end
subject { @summoner }
it { should be_kind_of(LolApi::Summoner) }
it { should respond_to(:id) }
it { should respond_to(:name) }
it { should respond_to(:profile_icon_id) }
it { should respond_to(... |
# frozen_string_literal: true
require 'rails_helper'
require 'support/error_details'
RSpec.describe 'search', type: :request do
include SchemaMatchers
include ErrorDetails
describe 'GET /v0/search' do
context 'with a 200 response' do
it 'should match the search schema', :aggregate_failures do
... |
# Copyright (c) 1999-2006 Minero Aoki
#
# This program is free software.
# You can distribute/modify this program under the same terms of ruby.
# see the file "COPYING".
require 'racc/parser'
module Racc
TRANSITION_TABLE_ATTRS =
[:action_table, :action_check, :action_default, :action_pointer,
:goto_t... |
execute "remove iptables" do
user "root"
command "rm -f /etc/sysconfig/iptables"
end
remote_file "/etc/sysconfig/iptables" do
owner "root"
group "root"
mode "644"
source "iptables"
end
service "iptables" do
action :stop
end
service "iptables" do
action :start
end
|
# require_dependency "usermanagement/application_controller"
#
# module Usermanagement
# class FamilyviewsController < ApplicationController
# before_action :set_familyview, only: [:show, :edit, :update, :destroy]
#
# # GET /familyviews
# def index
# @familyviews = Familyview.all
# end
#
# #... |
Point = Struct.new(:x, :y) do
def dist(c2)
(self.x - c2.x).abs + (self.y - c2.y).abs
end
def to_s
"(#{x}, #{y})"
end
end
def parse_coords(input)
input.lines.map do |line|
m = /(\d+), (\d+)/.match(line)
Point.new(m[1].to_i, m[2].to_i)
end
end
class Grid
attr_reader :coords
def initial... |
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
# Prevent database truncation if the environment is production
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'spec_helper'
require 'rspec/rails'
require 'devise'
require 'capybara/... |
class EventsController < ApplicationController
before_action :set_event, only: [:show, :edit, :update, :destroy, :register, :unregister]
before_action :check_user, only: [:edit, :update, :destroy]
# GET /events
# GET /events.json
def index
@events = Event.where(active: true)
@my_events = current_user.... |
require_relative '../base'
module Examples
module Checkout
class Walkthrough
def self.run(client)
if Clients::JSON === client
client.pending "Checkout::Walkthrough does not work with JSON client."
return
end
# Create the order step by step:
# You may als... |
# frozen_string_literal: true
lib = File.expand_path('lib', __dir__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'nz-whois/gem_version'
Gem::Specification.new do |spec|
spec.name = 'nz-whois'
spec.version = NZWhois::VERSION
spec.author = 'abrom'
spec.email = ... |
class CreateAreasOfInterest < ActiveRecord::Migration[5.1]
def change
create_table :areas_of_interest do |t|
t.string :file_id, null: false
t.integer :x, null: false, default: 0
t.integer :y, null: false, default: 0
t.integer :width, null: false
t.integer :height, null: false
t... |
class BeerClub < ActiveRecord::Base
has_many :memberships
has_many :members, through: :memberships, source: :user
def membership user
Membership.where(user_id:user.id, beer_club_id:self.id).first
end
def membershipconfirmed current_user
membership(current_user).confirmed
end
end
|
module Chanko
class ExceptionNotifier
include ActiveSupport::Callbacks
define_callbacks :notify
attr_accessor :message, :payload, :force
def self.notify(message, force, payload={})
self.new(message, force, payload).notify
end
def initialize(message, force, payload)
self.message =... |
class Subscription < ActiveRecord::Base
belongs_to :user
state_machine :state, initial: :new do
after_transition any => :pending_subscribe, :do => Proc.new {|subscription, *args| MailingList.subscribe(subscription.user)}
after_transition :subscribed => :pending_unsubscribe, :do => Proc.new {|subscription... |
class CreateApnDevices < ActiveRecord::Migration
def self.up
create_table :apn_devices do |t|
t.integer :user_id
t.string :device_token
t.boolean :active, :default=>true
t.string :alias
t.integer :tp
t.timestamps
end
add_index "apn_devices", ["device_token"], :name => ... |
require 'pry'
require_relative 'rps_rules.rb'
class AIPlayer
attr_accessor :name, :move, :wins
# Constructs the initial state of the Player object
#
# +name: a string representing the name of the player
# @move and @wins instance variables
def initialize(name:)
@name = name
@move = nil
@wins ... |
class RenameCodebooksTableToNotesTable < ActiveRecord::Migration
def change
rename_table :codebooks, :notes
end
end
|
module LevelObject
module Mixin
module Jumper
attr_accessor :jump_power
def jump_power
@jump_power ||= self.class.jump_power
end
def jump
@vel_y -= jump_power if on_ground?
end
end
end
end
|
class UserNotifier < ActionMailer::Base
layout 'mail'
helper :weekly_update
default :from => 'info@swipesense.com'
def welcome(user)
@user = user
mail :subject => 'Welcome to SwipeSense', :to => user.email, 'X-SMTPAPI' => {'category' => 'welcome'}.to_json
end
def weekly_update(user)
@unit = ... |
class CreateRecipeAlls < ActiveRecord::Migration
def change
create_table :recipe_alls do |t|
t.string :recipe
t.text :description
t.text :ingredients
t.text :directions
t.string :prep_time
t.string :cooking_time
t.timestamps
end
end
end
|
class AddDepartmentIdToGroups < ActiveRecord::Migration
def change
add_column :groups, :department_id, :integer
add_index :groups, :department_id
end
end
|
module TweetsHelper
def remove_hashtag_and_rating(tweet_text)
tweet_text
.strip
.gsub(/(\d\s*[+|-]?\s*)?#julysoundcheck$/i, '')
.gsub(/(\d\s*[+|-]?)$/, '')
.strip
end
def can_edit?(tweet)
return true if is_admin_user?
if twitter_user
tweet.screen_name == twitter_user.scr... |
describe "Rool::Email" do
before :each do
@data = {
foo: 'ryarthur262@gmail.com',
fizz: '@gmail.ryan',
cool_number: 262
}
end
describe '#process' do
## Expect True
it 'returns true if the datakeys value is probably an e-mail address' do
expect(Rool::Email.new(:foo).proc... |
require 'calabash-android/abase'
class BookingScreen < Calabash::ABase
include GoBike::AndroidHelpers
def trait
"* marked:'Check Fare'"
end
def tip_field
"* id:'et_tip'"
end
def promo_field
"* id:'et_promo_code'"
end
def noteToBiker
"* marked:'Note To Biker/Landmark'"
end
def tip
"* marked... |
class ApplicationController < ActionController::Base
protect_from_forgery
before_action :configure_sign_up_params, if: :devise_controller?
rescue_from RestClient::Forbidden, with: :handle_forbidden
rescue_from ActiveRecord::RecordNotFound, with: :handle_exception
rescue_from Net::SMTPAuthenticationError, with... |
class AddSlotsToVirtualMachine < ActiveRecord::Migration
def change
add_column :virtual_machines, :slots, :integer
end
end
|
class BookingMailer < ActionMailer::Base
def send_confirmation(booking)
@model = booking
return if booking.tenant.try(:from_email).blank? || booking.requestor.try(:email).blank?
# Send to the person requesting the hotel
mail from: booking.tenant.from_email, cc: [booking.client.try(:confirmation_emai... |
# frozen_string_literal: true
class CreateHouseholds < ActiveRecord::Migration[6.1]
def change
create_table :households do |t|
t.string :first
t.string :last
t.string :UIN
t.string :family
t.string :email
t.string :phonenumber
t.string :classification
t.string :maj... |
require 'spec_helper'
require 'tackle_box/email/editor'
describe TackleBox::Email::Editor do
let(:email) { File.join(File.dirname(__FILE__),'email.eml') }
subject { described_class.new(email) }
describe "#initialize" do
it "should set path" do
expect(subject.path).to be email
end
it "should ... |
# -*- mode: ruby -*-
# vi: set ft=ruby :
# Vagrantfile API/syntax version. Don't touch unless you know what you're doing!
VAGRANTFILE_API_VERSION = "2"
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
config.vm.box = "chef/centos-6.6"
config.omnibus.chef_version = "12.0.0"
config.vm.provider "virtualbo... |
require 'rails_helper'
RSpec.describe User, type: :model do
let(:company) { create :company }
let(:user) { build :user, company_id: company.id }
let(:user1) { create :user, email: 'a@a', company_id: company.id }
let(:user2) { create :user, email: 'a@a', company_id: company.id }
it 'is valid with a email, na... |
class CartItem < ActiveRecord::Base
belongs_to :cart
belongs_to :product
belongs_to :order
def increment_quantity
@quantity += 1
end
def total_price
quantity * price
end
def add_order order
self.update_attribute :order_id, order.id
end
end
|
# == Schema Information
#
# Table name: perks
#
# id :integer not null, primary key
# campaign_id :integer not null
# price :integer not null
# title :string not null
# description :text not null
# number_available :int... |
require "ruby_apollo/version"
require 'net/http'
require 'json'
require 'yaml'
require 'eventmachine'
module RubyApollo
class Error < StandardError; end
class ApolloClient
# HOST like 'https://xxx.com'
HOST = ''
attr_reader :project_name, :cluster, :namespace, :notification_map
def initialize(pr... |
class InsertTagBoilerPlate < ActiveRecord::Migration
def self.up
Tag.create([
{:name => 'comic book'},
{:name => 'super hero'},
{:name => 'dragon'},
{:name => 'epic'},
{:name => 'martial arts'},
{:name => 'samurai'},
{:name => 'sea'},
{:name => 'pirate'},
{:name => 'swords'},
{:name =>... |
#! /usr/bin/env ruby
# Inheritance
class Animal
def initialize
puts "Animal::initialize"
end
def speak(words)
puts "Animal::speak: " + words
end
def live
puts "Animal::live"
end
end
class Dog < Animal
def initialize name
@name = name
puts "Dog:#{@name}:initialize"
end
def spea... |
require 'test/unit'
require File.dirname(__FILE__) + '/../lib/client_date'
class ClientDateTest < Test::Unit::TestCase
include ClientDate::Helper
#
# format_date
#
def test_format_date
assert_equal "", format_date(nil)
assert_equal "<script>fd(2000,1,1,20,15,39);</script>", format_date(Time.gm(2000,... |
class Prefecture < ActiveHash::Base
self.data = [
{ id: 1, name: '--' },
{ id: 2, name: '北海道' },
{ id: 3, name: '青森県' },
{ id: 4, name: '岩手県' },
{ id: 5, name: '宮城県' },
{ id: 6, name: '秋田県' },
{ id: 7, name: '山形県' }
]
end
|
#!/usr/bin/env ruby
require "rubygems"
require "tile_engine"
require "lumber"
require "yaml"
require 'getoptlong'
require 'pp'
class WipeEngine < TileEngine
def initialize (cfg, logger, bbox, dry)
super(cfg,logger)
@dry = dry
@xmin = bbox[0][0].to_f
@ymin = bbox[0][1].to_f
@xmax = bbox[1][0].to_... |
# Launch School Printer (Part 1), User Input, Ruby Basics, Exercises
def printer
puts ">> How many output lines do you want? Enter a number >= 3: "
lines = nil
loop do
lines = gets.chomp.to_i
break if lines >= 3
puts ">> That's not enough lines."
end
lines.times {puts "Launch School is the best... |
class Admins::AdminMakersController < ApplicationController
before_action :authenticate_admins_admin_user!
def new
@maker = Maker.new
end
def create
@maker = Maker.new(maker_params)
@maker.save
redirect_to admins_admin_products_path
end
private
def maker_params
params.require(:maker).per... |
#!/usr/bin/env ruby
require 'logger'
log = Logger.new(STDOUT).tap do |log|
log.progname = 'coul-ruby'
end
log.debug "Loading gems"
require 'rubygems'
require 'bundler/setup'
Bundler.setup(:default)
$LOAD_PATH.unshift(File.dirname(__FILE__) + "/lib")
require 'version'
require 'parser'
require 'factory'
class Clien... |
module ApplicationHelper
def host
"http://#{APP_CONFIG['host']}"
end
end
|
require "./util/class_decorator"
class OptimalCountAgo
include ClassDecorator
attr_reader(
:time_ago,
:count
)
def initialize(time_ago, count)
@time_ago = time_ago
@count = count
end
def ==(another)
another != nil && another.time_ago == @time_ago && another.count == @count
end
en... |
require 'rspec'
require_relative '../lib/player'
describe Player do
describe "piece" do
it "should start as nil" do
expect(Player.new.piece).to be_nil
end
it "should be able to get and set a piece" do
player = Player.new
player.piece = 'X'
expect(player.piece).to eq('X')
... |
class FontMonoid < Formula
version "0.61"
url "https://github.com/larsenwork/monoid/blob/release/Monoid.zip?raw=true", verified: "github.com/larsenwork/monoid/"
desc "Monoid"
homepage "https://larsenwork.com/monoid/"
def install
(share/"fonts").install "Monoid-Bold.ttf"
(share/"fonts").install "Monoid... |
#!/usr/bin/env ruby
# -*- coding: binary -*-
require 'rex/peparsey'
require 'rex/pescan'
require 'rex/arch/x86'
require 'optparse'
def opt2i(o)
o.index("0x")==0 ? o.hex : o.to_i
end
#
# Right now this program is a bit shakey...
#
# - It tries to error on the side of caution, so it will try for a
# false negati... |
# class Animal
# def speak
# "Hello!"
# end
# end
# class GoodDog < Animal
# def speak
# super + " from GooDDog class"
# end
# end
# sparky = GoodDog.new
# p sparky.speak
class Animal
attr_accessor :name
def initialize(name)
@name = name
end
end
class GoodDog < Animal
def initialize(col... |
module Sal
class Engine < Temple::Engine
set_default_options :format => :html,
:generator => Temple::Generators::ArrayBuffer
use Sal::Parser, :file, :encoding
use Sal::Compiler
use Temple::HTML::Fast
filter :ControlFlow
filter :MultiFlattener # Collapse nested ... |
class MomentumCms::Api::SessionsController < MomentumCms::Api::BaseController
def create
# TODO: Add a hook that uses the user model's login method
mock_user = { id: 1, email: 'admin@momentum-cms.io' }
api_key = MomentumCms::ApiKey.create(scope: 'api')
mock_user[:api_key] = api_key
render json: {... |
# Dummy file to trick RSpec into actually running (and reporting 0 specs).
#
# I'm not clear on the best way to test this gem. For now, here is my
# process (and beware, it's not automated!):
#
# 1. Regenerate testbeds with `bin/generate-testbeds`.
#
# 2. Examine directory structure, particularly that `spec/testbed... |
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.belongs_to :cohort
t.string :name
t.string :email
t.text :bio
t.string :role
t.text :github
t.text :quora
t.text :twitter
t.text :facebook
t.text :linked_in
t.text ... |
require 'spec_helper'
describe Post do
before do
mock_geocoding!
theTailgate = FactoryGirl.create(:tailgate)
@post = FactoryGirl.create(:post, tailgate:theTailgate, user:theTailgate.user)
end
subject { @post }
it { should respond_to(:content) }
it { should respond_to(:tailgate) }
it {... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.