text stringlengths 10 2.61M |
|---|
# frozen_string_literal: true
module Dry
module Monads
# Represents an operation which either succeeded or failed.
#
# @api public
class Result
include Transformer
include ConversionStubs[:to_maybe, :to_validated]
# @return [Object] Successful result
attr_reader :success
... |
# frozen_string_literal: true
module Might
# Pagination middleware
#
class PaginationMiddleware
# @param app [#call, Proc]
# @param max_per_page [Integer]
# @param per_page [Integer]
#
def initialize(app, max_per_page: false, per_page: 50, paginator_class: Paginator)
@app = app
@ma... |
class CreateArticlesPhotosTable < ActiveRecord::Migration
def change
create_table :articles_photos, :id => false do |t|
t.references :article
t.references :photo
end
add_index :articles_photos, [:article_id, :photo_id]
end
end
|
# encoding: utf-8
module Coffeetags
VERSION = "0.1.2"
end
|
gem 'minitest', '~> 5.2'
require 'minitest/autorun'
require 'minitest/emoji'
require_relative 'chunker'
class Chunker_test < Minitest::Test
def test_it_receives_input_text
chunker = Chunker.new("input text/n")
assert_equal ("input text/n"), chunker.input_text
end
def test_it_can_split_text
chunker ... |
# encoding: utf-8
require_relative "sliding_piece.rb"
class Bishop < SlidingPiece
def move_dirs
[[1,1], [1,-1], [-1,1], [-1,-1]]
end
def white_symbol
"♗"
end
def black_symbol
"♝"
end
end |
# -*- encoding: utf-8 -*-
require File.expand_path('../lib/found/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ['Shannon Skipper']
gem.email = ['shannonskipper@gmail.com']
gem.description = %q{Find Street Address with CoreLocation}
gem.summary = %q{Find your street add... |
# frozen_string_literal: true
require 'rails_helper'
module Types
RSpec.describe CharacterType do
subject { described_class }
it { is_expected.to have_field(:id).of_type(!types.ID) }
it { is_expected.to have_field(:name).of_type('String!') }
it { is_expected.to have_field(:archetype).of_type('Strin... |
class Api::V1::StationsController < Api::V1::BaseController
before_action :admin_user_filter, only: [:destroy, :index, :create, :show]
def index
@stations = Station.all
render json: @stations
end
def show
@station = Station.find_by(id: params[:id])
if @station
... |
Rails.application.routes.draw do
root 'products#new'
delete 'delete_by_model_name', to: 'products#destroy'
resources :products
end
|
class Infection < ActiveRecord::Base
belongs_to :people
belongs_to :pathogens
end |
class AddLogoToOrganizationsAndCampaigns < ActiveRecord::Migration
def up
remove_column :organizations, :logo_file_name, :string
add_attachment :organizations, :logo
add_attachment :campaigns, :logo
end
def down
add_column :organizations, :logo_file_name, :string
remove_attachment :organizati... |
require "yt_id/version"
require "yt_id/regex"
module YTId
def self.from( url )
url.match( REGEX ) do |m|
m['id']
end
end
end
|
class NagerDateService < ApiService
def self.holiday_info
get_link("https://date.nager.at/api/v3/NextPublicHolidays/US")
end
def self.next_three_holidays
holidays = holiday_info.map do |data|
NagerData.new(data)
end
holidays[0..2]
end
end
|
#
# Author:: Celso Fernandes (<fernandes@zertico.com>)
# © Copyright IBM Corporation 2015.
#
# LICENSE: MIT (http://opensource.org/licenses/MIT)
#
Shindo.tests("Fog::Softlayer[:product] | Items model", ["softlayer"]) do
@service = Fog::Softlayer[:product]
tests("success") do
tests("#all") do
@items ... |
require 'test_helper'
class CotizmesexpsControllerTest < ActionDispatch::IntegrationTest
setup do
@cotizmesexp = cotizmesexps(:one)
end
test "should get index" do
get cotizmesexps_url
assert_response :success
end
test "should get new" do
get new_cotizmesexp_url
assert_response :success
... |
class DocFile < ActiveRecord::Base
belongs_to :document
validates_presence_of :docs_content_type
validates_presence_of :format
validates_presence_of :publication_code
# paperclip
has_attached_file :docs,
:path => "#{Constants::DOCFILES_PATH}:basename.:extension",
:url => "http://#{Constants::SIT... |
require 'net/http'
require 'json'
class ProductEditsController < ApplicationController
before_action :set_product_edit, only: [:destroy, :sync, :upload_image]
PRODUCT_EDITS_PER_PAGE = 10
# INDEX [HTTP GET]
#=====================================================================================================... |
class AddUsersFields < ActiveRecord::Migration
def self.up
add_column :users, :name, :string, null: false, default: "Stranger"
add_column :users, :surname, :string
add_column :users, :bday, :date
add_column :users, :gender, :string, null: false, default: "N/A"
add_column :users, :age, :in... |
class Agent < User
has_many :closed_tickets, foreign_key: :closer_id, as: :closer, class_name: 'Ticket'
def self.can_close_ticket?
true
end
def can_update_agent?(agent)
self.id == agent.id
end
def can_update_ticket?(ticket)
true
end
end |
dep 'vim' do
# requires 'vimrc', 'vim-vue', 'vim-sensible', 'vim-color-fresh'
met? do
# See if vim version supports clipboard
raw_shell('vim --version | grep +clipboard').stdout.empty?
end
meet do
log_shell 'installing vim with homebrew', 'brew install vim'
# log_shell 'cloning vim source', 'g... |
module SessionsHelper
def sign_in(user)
cookies.permanent[:remember_token] = user.remember_token
self.current_user = user
end
def signed_in?
!current_user.nil?
end
#TODO: comment out this function
# and then see if the assignment operator
# in the sign_in method would still work.
def current... |
class Context
def self.change_to (args)
requested_context = parse_args(args).join(' ')
if context_names.include? (requested_context)
find_and_create (requested_context)
else
puts "That's not a thing."
exit
end
end
private
def initialize (context, options)
@context = contex... |
require 'rails_helper'
RSpec.describe Donut::VocabularyValidationService do
describe '.valid?' do
subject { described_class.valid?(uri) }
context 'with valid Getty uri' do
let(:uri) { 'http://vocab.getty.edu/ulan/500180874' }
it { is_expected.to be(true) }
end
context 'with valid uri w... |
=begin
x Simple, given a string of words, return the length of the shortest word(s).
String will never be empty and you do not need to account for different data types.
=end
def shortest_word(statement)
empty_array = []
words = statement.split(" ")
words.each do |word|
empty_array.push(word.length)
en... |
class Post < ApplicationRecord
include Filterable
include LocaleContent
attr_accessor :image_file
validates :title_sv, :title_en, :content, presence: true
belongs_to :image, optional: true
has_many :taggings, as: :taggable
has_many :tags, through: :taggings
translates :title, :content
scope :tags,... |
module Tb
module V2
class Device < Grape::API
resource :device do
params do
requires :device_uid, type: String, desc: 'device uid.'
end
group do
before do
patient_authenticate!
status 200
end
desc '获取服药时间'
ge... |
def roll_call_dwarves(arr)
# Your code here
arr.each_with_index {|ele,index|puts "#{index + 1}. #{ele}"}
end
def summon_captain_planet(arr)
# Your code here
arr.map{|ele| "#{ele.capitalize}!"}
end
def long_planeteer_calls(var)
# Your code here
var.any?{|ele| ele.split(//).count > 4}
end
de... |
class Ember::FranchiseSerializer < ActiveModel::Serializer
attributes :id, :name, :user_ids, :image_url
def image_url
if @object.image.file.try(:size).present?
Rails.application.config.host + @object.image.url
else
nil
end
end
end
|
# frozen_string_literal: true
class PagesController < ApplicationController
include HighVoltage::StaticPage
# Order actually matters, this has to be after include HighVoltage::StaticPage
layout :layout_for_page
def index
@talk_summaries = TalkSummary.all
@featured_talk_summary = TalkSummary.last || Nu... |
require 'test/unit'
require_relative 'show'
class AdvancedConditionalGroupTest < Test::Unit::TestCase
def test_1
re = %r{ (?: (Mrs | Mr | Ms | Dr) \s )? (.*?) \s and \s }x
#Traduzione
# (?: XXX \s ) -> ?: significa che lo raggruppa ma non lo mette in una variabile $
# (Mrs | Mr | Ms | Dr) -> quell... |
require 'rails_helper'
RSpec.describe AuctionsController, type: :controller do
describe '#index' do
it 'renders index' do
get :index
expect(response).to render_template(:index)
end
end
describe '#show' do
it 'renders show' do
a = FactoryGirl.create(:auction)
a.save
get ... |
class UsersController < ApplicationController
# loads the signup page
# does not let a logged in user view the signup page
get '/signup' do
if !logged_in?
erb :'users/create_user', :layout => :'not_logged_in_layout'
else
redirect_to_home_page
end
end
# does not let user s... |
class ChangeColumnToTotal < ActiveRecord::Migration
def up
change_column :totals, :to_pay, :decimal, :precision => 11, :scale => 2, default: 0
change_column :totals, :paid, :decimal, :precision => 11, :scale => 2, default: 0
end
def down
change_column :totals, :to_pay, :integer
change_column :tot... |
module Playercenter::Backend::Venue
class Base
def friend(uuid1, uuid2, token, connection)
connection.graph.add_relationship(uuid1, uuid2, token, 'friends', 'direction' => direction)
end
protected
def direction
"outgoing"
end
end
end |
require "rails_helper"
describe 'visiting a event', :js => true do
before(:all) do
@event = create(:event)
end
it 'have all the information displayed in the screen' do
visit "/events/#{@event.slug}"
expect(page).to have_content @event.title
expect(page).to have_content @event.start.strftime('%d d... |
class DeveloperGame < ActiveRecord::Base
belongs_to :developer
belongs_to :game
validates_uniqueness_of :port_id, :scope => :developer_id
include GameIdSetter
end
|
class AddCommentToRegistrationEvaluationAnswers < ActiveRecord::Migration
def change
add_column :registration_evaluation_answers, :comment, :boolean, :default => false
end
end
|
class Shop < ActiveRecord::Base
include ShopifyApp::Shop
#private => disable all the options to customize the steps
#basic => normal setup of customized products
TYPES = %w{ private basic }
TYPES.each_with_index do |meth, index|
define_method("#{meth}?") { payment_type == meth }
end
def self.store(... |
class CreateArtists < ActiveRecord::Migration
class Artist < ActiveRecord::Base
end
def self.data
[
{ :id => 1, :artist => "--"},
{ :id => 718, :artist => "Stephen Sondheim"},
{ :id => 719, :artist => "Steve Perry"},
{ :id => 720, :artist => "Stevie Nicks"},
{ :id => 721, :art... |
module ApplicationHelper
def flash_alert
content_tag(:div, flash[:alert], class: 'alert alert-warning') unless flash[:alert].blank?
end
def qty_left(menu)
qty = menu.quantity - menu.ordered if menu.quantity
return qty
end
def collect_items(cart)
today = {}
cart.each do |item|
item... |
class FontNotoSerifThai < Formula
head "https://noto-website-2.storage.googleapis.com/pkgs/NotoSerifThai-unhinted.zip", verified: "noto-website-2.storage.googleapis.com/"
desc "Noto Serif Thai"
homepage "https://www.google.com/get/noto/#serif-thai"
def install
(share/"fonts").install "NotoSerifThai-Black.tt... |
case node[:platform]
when "centos", "amazon"
conf_path = "/etc/collectd.conf"
when "ubuntu"
conf_path = "/etc/collectd/collectd.conf"
end
if File.exist?(conf_path)
ruby_block "Rename old collectd.conf" do
block do
newname = conf_path + Time.now.utc.iso8601.gsub('-', '').gsub(':', '')
::Fi... |
require 'contest'
require 'redis'
require 'rack/test'
require 'sinatra/slaushed'
R = Redis.new(:db => 2)
class SinatraSlaushedTest < Test::Unit::TestCase
include Rack::Test::Methods
describe "Sinatra::Slaushed" do
setup do
R.flushdb
end
describe "Helpers" do
setup do
@app = Cla... |
Rails.application.routes.draw do
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
scope module: :users do
root 'home#index'
resources :home, only: [:index]
resources :categories, only: [:show]
resources :tags, only: [:show]
resources :products... |
class ContactMailer < ActionMailer::Base
default from: "from@example.com"
# Subject can be set in your I18n file at config/locales/en.yml
# with the following lookup:
#
# en.contact_mailer.message.subject
#
def delivermessage(mymessage)
mail(:to =>'bikeincrete@gmail.com',
:from =>mymessag... |
load "css.rb"
load "Bouttons_grille.rb"
load "Boutton.rb"
##
# Représentation d'une grille de jeu
##
# * +grille+ Une Gtk::Grid qui représente le plateau de jeu
# * +bouttons+ Tableau de boutons dans la grille
# * +css+ Les différents CSS utilisables
class Grille_jeu
attr_reader :grille
def initial... |
shared_examples "indexed_node" do
let(:zero) { described_class.new(0) }
let(:one) { described_class.new(1) }
let(:two) { described_class.new(2) }
let(:three) { described_class.new(3) }
let(:four) { described_class.new(4) }
let(:five) { described_class.new(5) }
let(:six) { described_class.new(6) }
let(... |
class Portfolio < ApplicationRecord
belongs_to :user
belongs_to :recipe
validates :user, uniqueness: true, if: :already_exist
def already_exist
self.user.recipes.include?(self.recipe)
end
end
|
require 'test_helper'
class ReadingTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
test "day#HourlyAverages" do
sample_readings = [
[20, 40, 60], # 00
[30, 40, 50], # 01
[10, 20, 30], # 02
[00, 30, 60], # 03
[80, 90, 100], # 04
[20, 60, 100], ... |
class CommentairesController < ApplicationController
before_action :set_chapitre
def new
@chapitre = Chapitre.find(params[:chapitre_id])
@commentaire = Commentaire.new
@user = current_user
end
def create
@commentaire = Commentaire.new(commentaire_params)
@commentaire.user = current_user
... |
require 'phoneme_loader'
class SyllableStructurer
def initialize
@sonority_by_type = build_sonority_hash
@phonemes = PhonemeLoader.phonemes_hash
end
def prepare_words read_words
read_words.map { |word|
syllables = group_phonemes word[:phonemes]
if syllables.length > 0
{:name => word[:na... |
require 'spec_helper'
describe 'RailsAdmin' do
context 'not logged in' do
it 'should redirect' do
get '/admin'
response.should be_redirect
end
end
context 'logged in' do
before do
login_as FactoryGirl.create(:admin), :scope => :user
end
it 'gets the dashboard' do
g... |
# == Schema Information
# Schema version: 20110314110640
#
# Table name: brands_instant
#
# id :integer(4) not null, primary key
# brand_id :integer(4)
# description :string(255)
# extended :text
# image_url :string(255)
# expires_at :datetime
# created_at :datetime
# updated_at :dateti... |
# frozen_string_literal: true
#= RoleAssignment
#
# Associates a Person with a Role, and optionally to a Resource
class RoleAssignment < Authegy::RoleAssignment
# Authegy::RoleAssignment already defines associations to :actor, :role and
# :resource
end
|
class ChattyUser
def initialize(chat_user_identifier)
@user = CHATTY_MODEL_NAME.constantize.send("find_by_#{CHATTY_USER_IDENTIFIER}", chat_user_identifier)
@chat_user_identifier = chat_user_identifier
end
def unread_message_details
Message.select('sent_by, count(*) as count').where(sent_to: @chat_use... |
module Nsn
class Twitterer
def initialize result = Result.latest
@client = client
@result = result
end
def call
if tweetable?
tweet
else
Nsn::Slack.new.call("[not_tweeted!]: #{text} #{condition}")
false
end
end
def tweetable?
@result.gr... |
class Everything
attr_accessor :id, :name, :author, :title, :description, :url, :urlToImage, :publishedAt
def initialize(source, author, title, description, url, urlToImage, publishedAt)
@id = source["id"]
@name = source["name"]
@author = author
@title = title
@description = description
@ur... |
require 'lita'
require 'net/http'
require 'uri'
require 'multi_json'
module Lita
module Handlers
class Recipe < Handler
config :api_key, required: true
route(/^recipe/, :recipe, command: true, help: { "recipe" => "random recipe" })
def recipe(response)
res = Net::HTTP.get_response(URI(... |
module LayoutHelper
def menu_button title, size = nil, items
button_class = case size
when :large then 'btn-lg'
when :small then 'btn-sm'
when :xs then 'btn-xs'
else ''
end
menu_items = items.map do |item|
if... |
#!/usr/bin/env ruby
class Alignment
attr_reader :read_name, :flag, :ref_name, :read_pos, :mapq, :cigar, :mate_ref, :mate_pos, :tlen, :seq, :phred, :tags, :cigar_totals
def initialize(line)
if line.split("\t").length < 12
$stderr.puts "This may not be a SAM record: #{line}"
return nil
end
... |
module TollFree
class Digit
def initialize number
@number=number
@LOOKUPHASH = {
2 => %w[a b c],
3 => %w[d e f],
4 => %w[g h i],
5 => %w[j k l],
6 => %w[m n o],
7 => %w[p q r s],
8 => %w[t u v],
9 => %w[w x y z]
}
end
def ... |
#
# Cookbook Name:: predictionio
# Recipe:: admin_user
#
# Copyright 2014 Makoto Kawasaki
#
# 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
#... |
require 'test_helper'
class Admin::ArticlesControllerTest < ActionController::TestCase
def test_should_get_index
get :index
assert_response :success
assert_not_nil assigns(:admin_articles)
end
def test_should_get_new
get :new
assert_response :success
end
def test_should_create_articles
... |
class Forecast < ActiveRecord::Base
# Helper methods for report lookups
include Reportable
belongs_to :user
validates_presence_of :company_name
validates :corporate_tax_rate, numericality: {
greater_than_or_equal_to: 0,
less_than: 100 ... |
require 'spec_helper'
require 'uri'
feature "Activity page", :js => true do
# need an activity with at least a open response question
let(:activity) { FactoryGirl.create(:activity_with_page_and_or) }
let(:user) { FactoryGirl.create(:admin) }
let(:activity_page) { activity.pages.first }
let(:questi... |
require 'spec_helper'
class EventSourceExample < EV::EventSource
def add_event(event)
apply(event)
end
protected
def handle(event)
end
end
RSpec.describe EventSourceExample do
describe '#changes' do
let(:events) { [1, 2] }
subject { described_class.new(events) }
context 'with events befo... |
class AddMonthToSessions < ActiveRecord::Migration[5.2]
def change
change_table :sessions do |t|
t.references :month, foreign_key: true
end
reversible do |migration|
migration.up do
change_column :sessions, :month_id, :integer, null: false
end
migration.down do
ch... |
# encoding: UTF-8
# Copyright 2012 Twitter, Inc
# http://www.apache.org/licenses/LICENSE-2.0
require 'spec_helper'
describe TwitterCldr::Utils::CodePoints do
describe '#to_char' do
it 'converts unicode code points to the actual character' do
expect(TwitterCldr::Utils::CodePoints.to_char(0x221E)).to eq('... |
require 'spec_helper'
describe "access server 1 map", :type => :feature do
it "should see the map when click over the link" do
server = Server.first
visit "/server/1"
map = server.maps.first
page.find(".linkmap-#{map.id}").click
page.should have_selector("#map")
end
end |
# => Contient la classe FenetreScores contenant l'affichage des meilleurs scores du jeu
#
# => Author:: Valentin, DanAurea
# => Version:: 0.1
# => Copyright:: © 2016
# => License:: Distributes under the same terms as Ruby
##
## classe FenetreScores
##
class FenetreScores < View
# VI box
@box... |
require 'socket'
require_relative 'logging'
require_relative 'request'
class SimpleServer
attr_reader :server, :level, :output, :host, :port, :request
READ_CHUNK = 1024 * 4
LOG = Logging.setup
LOG.debug("Logging is set up.")
def initialize(host='localhost', port=2345)
@host = host
@port = po... |
require 'spec_helper'
class StringTypecaster
def call(value, options)
value.to_s.ljust(options[:size], " ")
end
end
class IntegerTypecaster
def call(value, options)
value.to_s.rjust(options[:size], "0")
end
end
class ObjectFormatter
include Typecaster
attribute :name, :type => "string", :size =>... |
#!/usr/bin/env ruby
# frozen_string_literal: true
require 'English'
require 'date'
require 'erb'
require 'etc'
require 'fileutils'
require 'json'
require 'logger'
require 'net/http'
require 'optparse'
require 'pathname'
require 'time'
require 'tmpdir'
require 'uri'
require 'yaml'
class Error < StandardError; end
mod... |
class CreatePositions < ActiveRecord::Migration[5.1]
def change
create_table :positions do |t|
t.string :serial
t.float :latitude
t.float :longitude
t.float :press_zero
t.float :press_one
t.float :press_two
t.float :press_three
t.float :accel_x
t.float :accel_... |
require 'active_record'
require_relative './restriction_type/minimum_item_quantity.rb'
class Item < ActiveRecord::Base
belongs_to :currency
has_many :item_orders
has_many :minimum_item_quantity_restrictions,
class_name: "RestrictionType::MinimumItemQuantity"
has_many :orders, through: :item_orders
valid... |
class Admin::UsersController < ApplicationController
def initialize
super
@title = 'Users'
end
def index
@pagy, @users = pagy(filter, items: 10)
end
def new
@user = User.new
end
def create
@user = User.new(user_params)
@user.photo = params[:photo]
if @user.save
redire... |
class User < ApplicationRecord
validates :email, presence: true , uniqueness: true ,on: :create
validates :password_digest, presence: true, length: {in: 6..20}
has_secure_password
has_many :scores
end
|
fetch_description = "Script usage: rake fetch TICTAIL_EMAIL=<tictail-email> TICTAIL_PASSWORD=<tictail-password>"
require_relative '../../app'
desc fetch_description
task :fetch do
if !ENV['TICTAIL_EMAIL'] || !ENV['TICTAIL_PASSWORD']
puts fetch_description
exit
end
fetcher = Tictail::Fetcher.new(ENV['TIC... |
require_relative 'require_helper'
class CampaignParserOne
attr_reader :file
def initialize(file)
@file = file
end
def campaigns
@campaigns ||= parse_campaign_objects_from_file.sort_by { |campaign| campaign.date } unless @campaigns
end
private
def parse_campaign_objects_from_file
CSV.foreac... |
class AddImageUrlToDrug < ActiveRecord::Migration[5.0]
def change
add_column :drugs, :image_url, :string
end
end
|
class AddDispoToPuppies < ActiveRecord::Migration
def change
add_column :puppies, :dispo, :string
end
end
|
class AdminController < ApplicationController
skip_before_filter :validate_geo_restriction
before_filter :authenticate_admin!
load_and_authorize_resource :studio
rescue_from CanCan::AccessDenied do |exception|
redirect_to admin_studio_path(current_admin.studio), :alert => exception.message
end
prot... |
class Page < ActiveRecord::Base
belongs_to :website
has_many :sections, inverse_of: :page
validates_presence_of :website
end
|
class Node
attr_accessor :score, :children
def initialize(initial_score = nil, children = [])
@score = initial_score
@children = children
end
def add_child(node)
children << node
end
def score_node(node)
if node.score == nil
child_array = node.childr... |
class DashboardController < ApplicationController
before_filter :require_authentication
def show
@clients = current_account.clients
@authorizations = current_account.authorizations
end
end
|
# encoding: utf-8
module RbRotate
module StateModule
##
# State file archive section.
#
class Archive
##
# Holds the archive data.
#
@data
##
# Constructor.
... |
class GoodDog
attr_accessor :name, :height, :weight
def initialize(n, w, h)
@name = n
@height = h
@weight = w
end
def speak
"#{name} says Arf!"
end
def change_info(n, w, h)
self.name = n
self.height = h
self.weight = w
end
def info
"#{name} weighs #{weight} and is #{h... |
class ProgressAttachment < ActiveRecord::Base
mount_uploader :image, ProgressImageUploader
belongs_to :progress
validates :image, presence: true
end
|
class Api::UserAnswersController < ApplicationController
def create
@user_answer = UserAnswer.new(user_answer_params)
@user_answer.save!
render json: @user_answer
end
def index
@user_answers = UserAnswer.all
render json: @user_answers
end
def user_answer_params
params.require(:user_a... |
class PostsController < ApplicationController
before_action :set_post, only: [:show, :edit, :update, :destroy]
def index
@posts = Post.all
end
def show
@post = Post.find(params[:id])
end
def new
@post = Post.new
end
def create
@post = Post.new(post_params)
if @post.save
flash[:notice] = "New Pos... |
class CommentsController < ApplicationController
def index
comments = Comment.all
render json: comments
end
def create
comment = Comment.create(comment_params)
render json:{
text:comment.text,
id:comment.id,
user_id: comment.user_id,
chat_id: comment.chat_id,
creat... |
require 'rails_helper'
RSpec.describe 'admin merchants show (/admin/merchants/merchant_id)' do
let!(:merchant1) { create(:enabled_merchant) }
let!(:merchant2) { create(:enabled_merchant) }
let!(:merchant3) { create(:enabled_merchant) }
describe 'as an admin' do
context 'when I visit the admin merchants sh... |
class AddIndividualGoal1AndIndividualGoal2AndIndividualGoal3AndIndividualGoal4ToReviewReport < ActiveRecord::Migration
def self.up
add_column :review_reports, :individual_goal_1, :string
add_column :review_reports, :individual_goal_2, :string
add_column :review_reports, :individual_goal_3, :string
add... |
# frozen_string_literal: true
##
# A `Darlingtonia::RecordImporter` that processes files and passes new works
# through the Actor Stack for creation.
class MahoniaRecordImporter < Darlingtonia::RecordImporter
##
# @!attribute [rw] creator
# @return [User]
# @!attribute [rw] file_path
# @return [String]
... |
#!/usr/bin/ruby
# This example demonstrates the strategy pattern in the ruby language.
class Context
attr_accessor :strategy
def initialize
@strategy = ConcreteStrategy.new
end
def do(*args)
@strategy.do(*args)
end
end
class Strategy
def do(*args)
end
end
class ConcreteStrategy < Str... |
require 'open3'
module Util
class DbManager
attr_accessor :con, :stage_con, :pub_con, :event
def initialize(params={})
if params[:event]
@event = params[:event]
else
@event = Admin::LoadEvent.create({:event_type=>'',:status=>'',:description=>'',:problems=>''})
end
end
... |
#!/usr/bin/env ruby
require 'optparse'
$:.unshift('lib')
options = {}
ARGV.options do |opts|
opts.on('-t', "--type=FILE", String, "The type of zone file (either bind or tinydns)", "Default: bind") do |type|
options[:type] = type
end
opts.on('-d', "--debug", "Turn on debugging") do
options[:debug] = tru... |
class Page < ActiveRecord::Base
hobo_model # Don't put anything above this
fields do
name :string
text :text
timestamps
end
belongs_to :activity
has_many :page_panes, :order => :position
has_many :page_sequences
has_many :image_panes, :through => :page_panes, :source => :pane, :source_ty... |
class Api::PasswordsController < ApplicationController
def send_password_reset
if User.exists?(email: params[:email])
user = User.find_by email: params[:email]
user.send_reset_password_instructions
end
end
def set_new_password
user = User.with_reset_password_token(params[:token])
if u... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.