text stringlengths 10 2.61M |
|---|
require 'rails_helper'
RSpec.describe "Comments", type: :system do
describe "request/show comment" do
let!(:comment) { create :comment }
let!(:user) { create :user }
let!(:request) { create :request }
before do
log_in_as user
visit request_path(request.id)
end
it "comment create... |
class RenamePostsTableToArticles < ActiveRecord::Migration
def change
rename_table :posts, :articles
end
end
|
# frozen_string_literal: true
require 'rails_helper'
feature 'Editor edits an case' do
let(:this_case) { FactoryBot.create(:case) }
scenario 'Editor tries to save a case and fails' do
user = FactoryBot.create(:user)
login_as(user, scope: :user)
visit '/cases/new'
click_button 'Create Case'
exp... |
class AddTimeToRace < ActiveRecord::Migration
def change
add_column :races, :time, :datetime
end
end
|
require 'csv'
require 'optparse'
require 'terminal-table'
require_relative 'batting_average'
options = { filters: {} }
OptionParser.new do |opts|
opts.banner = 'Usage: ruby calculate.rb [options]'
opts.on('--batting_file_path=PATH', 'Batting CSV path (./data/Batting.csv)') do |value|
options[:batting_file_p... |
require 'bundler/capistrano'
require 'rvm/capistrano'
load 'deploy/assets'
default_run_options[:pty] = true
# deploy config
set :user, 'user'
set :domain, 'example.com'
set :application, 'notin'
set :deploy_to, '/path/to/deployment/dir'
set :deploy_via, :remote_cache
set :keep_releases, 5
set :static_configs, %w(da... |
class DancingOctopus
TILES_ARRAY = ["up", "right-up", "right", "right-down", "down", "left-down", "left", "left-up"]
TILES_HASH = {
"up" => 0,
"right-up" => 1,
"right" => 2,
"right-down" => 3,
"down" => 4,
"left-down" => 5,
"left" => 6,
"left-up" => 7
}
# O(n)
def slow_dance(d... |
class Ability
include CanCan::Ability
def initialize user
user ||= User.new
if user.admin?
can :manage, :all
elsif user.supervisor?
can :manage, :all
cannot :manage, Subject
else
can [:update, :read], User, id: user.id
can [:read], Task
can [:create], UserTask, u... |
require 'spec_helper'
describe 'ck::source::git', :type => :class do
$supported_os.each do | os_expects |
os = os_expects[:os]
facts = os_expects[:facts]
expects = os_expects[:expects]
context "on #{os}" do
let (:facts) { facts }
describe "with no parameters" do
it { should... |
# frozen_string_literal: true
module SFRest
# List codebases on the factory.
class Codebase
# @param [SFRest::Connection] conn
def initialize(conn)
@conn = conn
end
# Lists the codebases
# @return [Hash] A hash of codebases configured for the factory.
# { "stacks" => { 1 => "abcde", ... |
require 'rails_helper'
RSpec.describe Messages::AuthMessages do
describe '#not found' do
it 'returns message' do
expect(described_class.not_found).to eq('Sorry, record not found')
end
end
describe '#unauthorized' do
it 'returns message' do
expect(described_class.unauthorized).to eq('Unau... |
namespace :course_autocompletes do
desc "Generate course search item"
task :index => :environment do
CourseAutocomplete.index_courses
end
end
|
class Movie < ActiveRecord::Base
validates:title,presence:true
validates:release_date,presence:true
validate:released_1930_or_later
validates_length_of:title,minimum:3
validates:title,uniqueness:true
before_validation :capitalize_title
def capitalize_title
self.title = self.title.strip
self.titl... |
require_relative 'test_helper'
class BasicParsingTests < SlightishTest
suite('empty suite', '').should do |s|
assert_empty(s.test_cases)
end
suite('simple command', %[
$ echo 2
]).should do |s|
assert_equal(1, s.test_cases.length)
assert_case(s.test_cases[0], 'echo 2', [1, 1])
end
suite('... |
module Kaya
module Support
class QueryString
attr_reader :values, :req
# req = Request
def initialize req
@req = req
@values = Rack::Utils.parse_nested_query(req.query_string.split("/").last)
end
def value_for key
@values[key]
end
def method_mi... |
#
# Cookbook Name:: localdev
# Recipe:: php7
#
# Copyright (c) 2016 iamota, All Rights Reserved.
execute "apt-get install python-software-properties" do
command "apt-get install python-software-properties -y"
action :run
end
execute "add-apt-repository ppa:ondrej/php" do
command "add-apt-repository ppa:ondrej/php ... |
# frozen_string_literal: true
require 'test_helper'
module Vedeu
module Renderers
describe Text do
let(:described) { Vedeu::Renderers::Text }
let(:instance) { described.new(options) }
let(:options) {
{
compression: compression,
end_tag: end_tag,
... |
class EventsController < ApplicationController
def index
@events = Event.page params[:page]
@participants = Participant.all
end
def new
@event = Event.new
@users = User.all
end
def show
@event = Event.find(params[:id])
@items = @event.items.page(params[:page]).per(5)
end
def cre... |
class StoresController < ApplicationController
load_and_authorize_resource
# GET /stores
#-----------------------------------------------------------------------
def index
@stores = Store.all
respond_with(:admin, @stores)
end
# GET /stores/1
#-----------------------------------------------------... |
# -*- encoding : utf-8 -*-
# The model of the genre resource.
#
# This code is part of the Stoffi Music Player Project.
# Visit our website at: stoffiplayer.com
#
# Author:: Christoffer Brodd-Reijer (christoffer@stoffiplayer.com)
# Copyright:: Copyright (c) 2014 Simplare
# License:: GNU General Public License (stoffi... |
class SubleasesController < ApplicationController
before_action :set_sublease, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!, except: [:show, :index]
load_and_authorize_resource
# GET /subleases
# GET /subleases.json
def index
@subleases = Sublease.all
end
def priv_s_... |
class AddArchetypeToArtists < ActiveRecord::Migration
def change
add_reference :artists, :archetype, polymorphic: true, index: true
end
end
|
require 'spec_helper'
describe AdminMenuController do
describe 'an admin user' do
let(:admin) { FactoryGirl.create(:admin) }
before { sign_in admin }
it 'gets show page' do
get :show
expect(response).to be_successful
expect(response).to render_template(:show)
end
end
describe... |
module IPTables
class Rule
class << self
def add_custom_matcher(name,flag=nil,&block)
if flag.nil? && name.is_a?(Hash)
flag = name.values.first
name = name.keys.first
end
define_method "add_#{name}" do |arg|
instance_variable_set "@#{name}", arg
... |
require 'minitest/autorun'
require_relative 'test_helper'
include FileMover
class ErrorSink < FileMover::Dir
def put_files pathes
raise StandardError, "putting #{pathes} failed"
end
end
class SourceTest < MiniTest::Unit::TestCase
include TestHelper
def test_on_success_empty
Tempfile.new 'foo' do ... |
class OparationMember::ParticipatesController < ApplicationController
before_action :set_party
def update
new_member_ids = []
new_member_ids = @party.member_ids << params[:member_id]
@party.member_ids = new_member_ids
redirect_to party_path(@party)
end
def destroy
new_member_ids = []
n... |
#!/usr/bin/ruby
require_relative 'github_archiver'
begin
gh = GithubArchiver.new(ARGV)
rescue InvalidInput => e
puts e.message
puts GithubArchiver.show_usage
exit(1)
end
results = gh.execute
puts "\nResults\n------------------------"
results.each do |k,v|
puts "#{k} - #{v} events"
end |
module ModalHelper
def default_options
return {:id => 'modal', :size => '', :show_close => true, :dismiss => true}
end
#modals have a header, a body, a footer for options.
def modal_dialog(options = {}, &block)
opts = default_options.merge(options)
content_tag :div, :id => options[:id], :class =... |
def select_even_nums(array)
array.select(&:even?)
end
def reject_puppies(array)
array.reject {|puppy| puppy['age'] < 3}
end
def count_positive_subarrays(array)
array.count {|subs| subs.sum > 0}
end
def aba_translate(word)
vowels = 'aeiou'
str = ''
word.each_char do |char|
if vowels.... |
class AddHasCollarToCritters < ActiveRecord::Migration
def change
add_column :critters, :has_collar, :boolean, default: false
end
end
|
# 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 Lice... |
module QBIntegration
module Service
class Bill < Base
attr_reader :payload, :bill, :purchase_order, :purchase_order_service, :line_service
def initialize(config, payload)
@payload = payload
@bill = payload[:bill]
@purchase_order_service = PurchaseOrder.new(config, payload)
... |
class Libfabric < Formula
desc "OpenFabrics libfabric"
homepage "https://ofiwg.github.io/libfabric/"
url "https://downloads.openfabrics.org/downloads/ofi/libfabric-1.2.0.tar.bz2"
sha256 "179da0e27b47ca35b5ec823c30cdcc63cf991f0f86bfd655e091a1268d1a3182"
bottle do
sha256 "fb5c566ee556d050f53f19568f752cb5ba... |
class CreateMessages < ActiveRecord::Migration
def change
end
def up
create_table :messages do |t|
#id created automatically and is primary_key
t.integer :thread_id
t.integer :thread_length
t.integer :note_id
t.integer :sender_user_id
t.integer :reciever_user_id
... |
def range(first, last) # Array of numbers btwn first, last
return [first] if first == last
[first].concat( range(first + 1, last) )
end
def exponent(b, n) # Exponentiation
return 1 if n == 0
b * exponent(b, n - 1)
end
def exp(b, n) # Faster Exponentiation
return 1 if n == 0
return b if n == 1
i... |
class CreateCars < ActiveRecord::Migration[5.1]
def change
create_table :cars, id: :string do |t|
t.string :name
t.decimal :horsepower
t.decimal :price
t.string :cars_type_id
t.timestamps
end
add_index :cars, :car_type_id
add_foreign_key :cars ,:cars_types
end
end
|
class Location
attr_reader :latitude, :longitude
def initialize(response)
location = response["results"].first&.dig("geometry", "location")
@latitude = location&.dig("lat")
@longitude = location&.dig("lng")
end
def success?
true
end
end
|
require 'carrierwave/test/matchers'
require 'spec_helper'
RSpec.describe ApplicationUploader, type: :uploader do
include CarrierWave::Test::Matchers
let(:user_profile) { build(:user_profile) }
let(:uploader) { ApplicationUploader.new(user_profile, :avatar) }
describe 'with a test url' do
before do
A... |
class NirTypesController < ApplicationController
before_action :set_nir_type, only: [:show, :edit, :update, :destroy]
# GET /nir_types
# GET /nir_types.json
def index
@nir_types = NirType.all
end
# GET /nir_types/1
# GET /nir_types/1.json
def show
end
# GET /nir_types/new
def new
@nir_t... |
# XSD4R - XML Schema Datatype 1999 support
# Copyright (C) 2001, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
# redistribute it and/or modify it under the same terms of Ruby's license;
# either the dual license version in 2003, or any later ve... |
module Backend
# Comments controller
class CommentsController < BackendController
# POST /
# Creates a comment by a user
def create
@comment = post.comment_threads.build(comment_params.merge!({user_id: current_user.id}))
if @comment.save
render :partial => "backend/comments/show", ... |
class DevicesController < ApplicationController
before_action :load_device, only: [:edit, :update, :destroy]
before_action :load_customer, only: [:new, :create]
before_action :authenticate_user!
def new
@device = Device.new
@customer.devices.build
end
def edit
@customer = @device.customer
en... |
class Nanny < Profile
has_many :schedules, :dependent => :destroy
has_many :cases
has_many :ratings, through: :cases
has_many :items, through: :ratings
belongs_to :user
has_one :info
def check_schedule?(session)
schedules = self.schedules.where("start_date>=? and start_date < ?",start_date(session),end_... |
# Creates a task to support seed fixtures
# - Store this file in lib/tasks/seed_fixtures.rake
# - Place fixtures in db/seed
# - Use with 'rake db:seed'
namespace :db do
desc "Load seed fixtures into the current environment's database."
task :seed => :environment do
require 'active_record/fixtures'
seed_di... |
class PicturesController < ApplicationController
swagger_controller :pictures, "Pictures management"
before_action :authenticate_volunteer!, unless: :is_swagger_request?
before_action :set_picture, only: [:delete, :update]
before_action :check_rights, only: [:create]
swagger_api :create do
summary ... |
FactoryGirl.define do
factory :fabric, class:Fabric do
creator
updater
factory :blue_flannel do
name 'blue flannel'
end
#factory :red_cotton, class: Fabric, aliases: [:fabric] do
factory :red_cotton, aliases: [:red_cotton_fabric] do
name 'red cotton'
end
factory :white_cotton do
name 'whit... |
class CreateDependentProduct < ActiveRecord::Migration
def self.up
create_table :dependent_products do |t|
t.integer :product_id
t.integer :dependency_id
t.timestamps
end
end
def self.down
drop_table :dependent_products
end
end
|
class CreateProjectworkflowitvendorRelationships < ActiveRecord::Migration[5.1]
def change
create_table :projectworkflowitvendor_relationships do |t|
t.integer :project_workflow_id
t.integer :tag_itvendor_id
t.timestamps
end
end
end
|
# frozen_string_literal: true
require "strscan"
module FuelSurcharge
class HTMLScanner
def initialize(source)
@scanner = StringScanner.new(source.to_s)
end
def upcoming(tag, attribute = nil)
return if @scanner.eos?
opening = attribute ? "<#{tag}\s[^>]*#{attribute}[^>]*>" : "<#{tag}[^... |
# frozen_string_literal: true
class ErrorsController < ActionController::Base
protect_from_forgery with: :null_session
rescue_from StandardError, with: :internal_server_error
rescue_from ActiveRecord::RecordNotFound, with: :not_found
def show
raise request.env['action_dispatch.exception']
end
def not_... |
Given /^on cobot I have a space "([^\"]*)"$/ do |space_name|
subdomain = space_name.gsub(/\W+/, '-')
OmniAuth.config.mock_auth[:cobot] = {
"provider"=>"cobot",
"uid"=>"janesmith",
"credentials"=>{"token"=>"12345"},
"info"=> {
"email"=>"janesmith@example.com"},
"extra"=> {
"raw_info"... |
require "spec_helper"
require "solr/core"
describe "Supernova::Solr::Core" do
let(:url) { "http://path.to.solr:1122" }
let(:core_url) { "http://path.to.solr:1122/solr/my_core" }
let(:body) { { :a => 1 }.to_json }
let(:core) { Supernova::Solr::Core.new(url, "my_name") }
describe "#initialize" do
it "... |
class RenameWodWOrkoutGroupIdField < ActiveRecord::Migration[5.2]
def change
rename_column :wods, :workout_group_id, :workout_id
end
end
|
class RenameColumnAtCompanyContacts < ActiveRecord::Migration
def change
rename_column :company_contacts, :telefonnumber, :telephone_number
end
end
|
class CreatePatients < ActiveRecord::Migration[5.1]
def change
create_table :patients do |t|
t.string :name
t.date :admitted_on
t.string :emergency_contact
t.string :blood_type
t.references :doctor, foreign_key: true
#t.references :room, foreign_key: true
t.timestamps
... |
require 'test_helper'
class CreatingBooksTest < ActionDispatch::IntegrationTest
test 'creates new book if data is valid' do
post '/api/books', { book: {
title: 'Emma',
rating: 3,
author: 'Jane Austen',
genre_id: 1,
review: 'Not as good as the movie Clueless',
amazon_id: '12345... |
require "spec_helper"
describe AmazonTokenGenerator::Token do
let(:redis) { AmazonTokenGenerator.redis = Redis::Namespace.new(:token_generator, redis: Redis.new) }
let(:project) { create(:project) }
let(:token) { AmazonTokenGenerator::Token.fetch("sts:project:#{project.id}") }
before(:each) { redis.flushdb }
... |
class Genymotion < Cask
url 'https://ssl-files.genymotion.com/genymotion/genymotion-2.0.3/genymotion-2.0.3.dmg'
homepage 'http://www.genymotion.com/'
version '2.0.3'
sha1 '4124868d90befe69e2448f7c8b714c2a2819f082'
link 'Genymotion.app', 'Genymotion Shell.app'
end
|
# frozen_string_literal: true
# Copyright (c) 2018-2020 Yegor Bugayenko
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the 'Software'), to deal
# in the Software without restriction, including without limitation the rights
# to us... |
class RemoveTimestampsFromQuestion < ActiveRecord::Migration
def change
remove_column :questions, :created_at, :string
remove_column :questions, :updated_at, :string
end
end
|
require 'spec_helper'
describe Xlineitem do
let(:xferslip) { FactoryGirl.create(:xferslip) }
before do
@lineitem = xferslip.xlineitems.build(listid: "123456",
itemnumber: 5454,
desc1: "Widget",
quantity: 4,
xferslip_id: xferslip.id)
end
subject { @lineitem }
it { shoul... |
class AddColumnsToInvoice1A < ActiveRecord::Migration
def change
add_column :invoices, :memo, :string
add_column :invoices, :fob, :string
add_column :invoices, :emailed, :boolean
add_column :invoices, :email, :string
add_column :invoices, :tracking, :string
add_column :invoices, :ship_method, ... |
# typed: true
# frozen_string_literal: true
require 'test_helper'
module Ffprober
module Ffmpeg
class ExecTest < Minitest::Test
class FakeFinder
attr_accessor :path
end
def test_output_without_ffmpeg
finder = FakeFinder.new
finder.path = nil
exec = Ffprober::Ff... |
require "spec_helper"
describe Eshealth::HttpRequest do
describe "Attributes" do
httprequest = Eshealth::HttpRequest.new
describe ".url" do
it "Should allow reading and writing" do
httprequest.url = "http://somethingstupid.com"
expect(httprequest.url).to eq("http://somethingstupid.com")... |
module ApplicationHelper
def active_class(link_path)
url = link_path.split( "\">" )[ 1 ][ 0..-5 ]
current_page?( url ) ? "current" : ""
end
def active_class_for_dash( link_path )
url = link_path.split( "\">" )[ 1 ][ 0..-5 ]
current_page?( url ) ? "active" : ""
end
def resource_name
:user... |
class Post < ApplicationRecord
has_attached_file :image
validates_attachment :image,
content_type: { content_type: /\Aimage\/.*\z/ },
size: { less_than: 1.megabyte }
end
|
class Admins::BrandsController < Admins::BaseController
before_action :set_brand, only: [ :show ]
def index
@brands =
(if params[:q].present?
Brand.search("*#{params[:q]}*").records.page(params[:page]).per(100)
else
Brand.top
end)
respond_to do |format|
format.htm... |
#!/usr/bin/env ruby
# Requirements: gem install dm-postgres-adapter, gem install data_mapper
require 'dm-core'
DB_REPOSITORY = ENV['RACK_ENV']
# Comment the upper line and uncomment the line below if you plan to use this module without Sinatra (app.rb).
# Make sure your database.yml file has correct credentials and... |
class CalculationController < ApplicationController
before_action :check_authorized, except: :show
def show
respond_to do |format|
format.html
end
end
def create
cs = CalculationService.new(dataset: params[:dataset])
if cs.call
result = {
min: cs.sorted_vector.first... |
FactoryGirl.define do
factory :user do
email { Faker::Internet.safe_email }
password 'secret123'
password_confirmation 'secret123'
confirmed_at Time.now
factory :user_with_profile do
profile { create(:profile) }
end
end
end
|
class AddEmployeeRefusedToReviewReport < ActiveRecord::Migration
def self.up
add_column :review_reports, :employee_refused, :boolean, :default => false
end
def self.down
remove_column :review_reports, :employee_refused
end
end
|
class SlideShipmentProcessor < ShipmentProcessor
attr_accessor :patient, :specimen
def process(message)
Shoryuken.logger.info "#{self.class.name} | Processing tissue specmen shipped message: #{message}"
begin
@specimen = NciMatchPatientModels::Specimen.query_latest_tissue_specimen_by_patient_id(me... |
Paintbox::Application.routes.draw do
resources :sessions, :only => [:new, :create, :destroy]
resources :swatches
resources :users do
resources :swatches
end
# match ':username', :to => 'users#show'
match 'signup', :to => 'users#new', :as => :signup
match 'login', :to => 'sessions#new... |
# encoding: UTF-8
# Copyright 2012 Twitter, Inc
# http://www.apache.org/licenses/LICENSE-2.0
module TwitterCldr
module Tokenizers
class RbnfTokenizer
def tokenize(pattern)
PatternTokenizer.new(nil, tokenizer).tokenize(pattern)
end
private
def tokenizer
@tokenizer ||= b... |
module Griddler
module Mailin
class Adapter
def initialize(params)
if params['mailinMsg'].is_a? String
@params = JSON.parse(params['mailinMsg'])
else
@params = params['mailinMsg']
end
end
def self.normalize_params(params)
adapter = new(params)... |
class ClustersController < ApplicationController
# GET /clusters
# GET /clusters.json
def index
@clusters = Cluster.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @clusters }
end
end
# GET /clusters/1
# GET /clusters/1.json
def show
@cl... |
require 'rubygems'
desc "initialize environment"
task :env do
require File.join('.', 'config', 'environment.rb')
end
namespace :db do
desc "DESTRUCTIVE bootstrap of the database"
task :bootstrap => :env do
puts "Bootstrapping database..."
DataMapper.auto_migrate!
end
desc "non-destructive migratio... |
require "matrix"
module Primes
class MultiplicationTable
attr_reader :across, :down
def initialize(number_range)
@across = @down = number_range.to_a
@matrix = Matrix.build(number_range.count) { |row, col|
across[col] * down[row]
}
end
def column(index)
matrix.column(... |
module TestBench
class Run
module Substitute
def self.build
Run.new
end
class Run < Fixture::Run::Substitute::Run
def output
@output ||= Output::Substitute.build
end
def start
output.start_run
end
def started?
outpu... |
require 'spec_helper'
require 'testdata'
require 'topicz/commands/path_command'
describe Topicz::Commands::PathCommand do
it 'raises an error when it matches multiple topics' do
with_testdata do
expect {
Topicz::Commands::PathCommand.new(nil, []).execute
}.to raise_error(/Multiple topics mat... |
class TransitFund < ActiveRecord::Base
VALID_SOURCES = %w(dwolla stripe etrade)
validates :source, :presence => true, :inclusion => { :in => VALID_SOURCES }
VALID_DESTINATIONS = %w(dwolla stripe etrade)
validates :destination, :presence => true, :inclusion => { :in => VALID_DESTINATIONS }
end
|
class UsersController < ApplicationController
def update
preveous_username = set_user.username
respond_to do |format|
if set_user.update!(user_params)
format.js
end
end
new_username = @user.username
room_id_for_room_channel = @user.room_id
ActionCable.server.broadcast "roo... |
# frozen_string_literal: true
module Tasks
# MigrationClassGenerator
class MigrationClassGenerator
def self.generate(name)
classname = name.split('_').map(&:capitalize).join
<<~CONTENTS
# frozen_string_literal: true
# #{classname}
class #{classname} < ActiveRecord::... |
include MatchesHelper
class ConversationsController < ApplicationController
before_action :login_user
def create
match = Match.find(params[:id])
Message.create(
match_id: match.id,
message_text: params[:text],
user_id: params[:author],
recipient_id: get_matched_user(match, ... |
class EARMMS::StaticController < EARMMS::ApplicationController
VENDOR_WHITELIST = [
"/purecss/build",
"/font-awesome/css",
"/font-awesome/fonts",
"/zxcvbn/dist",
]
configure do
scsspath = File.join(EARMMS.root, "assets", "scss")
viewspath = File.join(EARMMS.root, "app", "views")
set(... |
class CreatePrepSessions < ActiveRecord::Migration
def change
create_table :prep_sessions do |t|
t.integer :status
t.string :comments
t.string :created_by
t.timestamps null: false
end
end
end
|
#!/usr/bin/env ruby
require 'yaml/store'
class Giftee
attr_reader :name, :forbidden_gifters
def initialize(name, *forbidden_gifters)
@name = name
@forbidden_gifters = (forbidden_gifters << name).compact
end
def random_gifter_name(candidates)
(candidates - forbidden_gifters).sample
end
end
cla... |
class Placenet < ActiveRecord::Base
belongs_to :user
belongs_to :showplace
attr_accessible :user_id, :showplace_id
end
|
Rails.application.routes.draw do
resources :items
root 'static_pages#home'
get 'about', to:'static_pages#about'
get 'catalog', to:'static_pages#catalog'
get 'admin', to:'static_pages#admin'
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
|
class AddFieldsToIssue < ActiveRecord::Migration[5.0]
def change
add_column :issues, :project_id, :integer
add_column :issues, :due_date, :date
end
end
|
module Useful_Methods
attr_reader :max_capacity
attr_accessor :current_items
def initialize(max_capacity = 10)
@max_capacity = max_capacity
@current_items = []
end
def full?
@current_items.length == max_capacity
end
def add_item
@current_items << Box.new
end
def add_item(first_nam... |
# frozen_string_literal: true
# Usage in model:
# serialize :proto, Proto::Message::Name
#
# Usage in extension config:
# Proto::Message::Name.extend(ProtoSerialize)
#
module ProtoSerialize
# Decode
def load(data)
data ? decode(data) : new
end
# Encode
def dump(data)
case data
when self
... |
class String
def palindrome?
newString=self.downcase.gsub(/\W/, '')
return newString == newString.reverse
end
end
puts "foo".palindrome?
puts "abba".palindrome?
module Enumerable
def palindrome?
self == self.reverse
rescue NoMethodError
puts "Without method: reverse"
end
end
puts [1,2,3,2,1].pali... |
class Sample < ActiveRecord::Base
belongs_to :piste
enum state: [ :open, :in_preparation, :closed ]
end
|
require 'xmlss/writer'
require 'xmlss/element_stack'
require 'xmlss/style/base'
require 'xmlss/element/worksheet'
module Xmlss
class Workbook
def self.writer(workbook)
workbook.instance_variable_get("@__xmlss_writer")
end
def self.styles_stack(workbook)
workbook.instance_variable_get("@__xm... |
Rails.application.routes.draw do
devise_for :users
root 'page#index'
get 'inventories/show'
get '/players/new/:character_id' => 'players#new', as: :new_player
match '/players/current' => 'players#set_current', as: :set_current, via: [:post]
resources :characters, only: :index
resources :players, except... |
class TopicsController < ApplicationController
prepend_before_action :authenticate_user!
before_action :set_topic, only: [:show, :edit, :update, :destroy]
# GET /topics
# GET /topics.json
def index
@topics = Topic.order(updated_at: :desc).page(params[:page]).per(10)
@counts = User.find(current_user.... |
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'tachyons-sass/rails/version'
Gem::Specification.new do |spec|
spec.name = "tachyons-sass-rails"
spec.version = TachyonsSass::Rails::VERSION
spec.authors = ["Gerard Simp... |
require 'csv'
require 'awesome_print'
require 'pry'
class Customer
attr_reader :id, :customer
attr_accessor :email, :address, :customers
def initialize(id, email, address)
@id = id
@email = email
@address = address
end
def self.all
csv_data = CSV.read("data/customers.csv")... |
class EventsController < ApplicationController
before_action :get_user
before_action :set_event, only: [:edit, :update, :destroy, :show]
def show
end
def index
@events = @user.events
end
def new
# just show the new event form view
@event = @user.events.new
end
def edit
# implicit s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.