Active Record Without a Rails App

Original Source: http://blog.teamtreehouse.com/active-record-without-rails-app

When you want to work with Ruby on Rails models, even if you’re just playing around, you have to go through a few steps:

Create an app directory
Create a database
Generate model classes
Run migrations

But sometimes you need something much more lightweight. When I was creating code challenges for our new Active Record Associations in Rails course recently, I needed to simulate a full Rails environment without actually loading Rails (which would have been too slow). So I created a setup that:

Loads just the Active Record library, not all of Rails
Creates a database entirely in RAM, not on disk
Sets up the database without running migrations

I wanted to share my results with all of you, so you can experiment with new Rails models without having to create full Rails apps.

Start learning to code today with a free trial on Treehouse.

The Code

The bulk of our simulated Rails app resides in a single file. This particular setup mimics an app for a veterinary office, including an Owner model that has_many instances of a Pet model. (But you can substitute model classes of your own, if you want).

Create a file named vet.app, in any folder you want, and paste in this code. (We’ll explain all the code in a bit.)

File: vet.rb

# Instead of loading all of Rails, load the
# particular Rails dependencies we need
require ‘sqlite3’
require ‘active_record’

# Set up a database that resides in RAM
ActiveRecord::Base.establish_connection(
adapter: ‘sqlite3’,
database: ‘:memory:’
)

# Set up database tables and columns
ActiveRecord::Schema.define do
create_table :owners, force: true do |t|
t.string :name
end
create_table :pets, force: true do |t|
t.string :name
t.references :owner
end
end

# Set up model classes
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
end
class Owner < ApplicationRecord
has_many :pets
end
class Pet < ApplicationRecord
belongs_to :owner
end

Now to actually use these models. In the same folder, create another file (you can name it anything you want).

File: your_code.rb

# Load the above file
require ‘./vet’

# Play around!
owner = Owner.create(name: “Jay”)
owner.pets.create(name: “Max”)
owner.pets.create(name: “Chai”)
p Owner.first.pets

If you run the above file from your terminal, the model objects will be created and saved to the in-memory database!

$ ruby your_code.rb
— create_table(:owners, {:force=>true})
-> 0.0193s
— create_table(:pets, {:force=>true})
-> 0.0008s
#<ActiveRecord::Associations::CollectionProxy [
#<Pet id: 1, name: “Max”, owner_id: 1>,
#<Pet id: 2, name: “Chai”, owner_id: 1>
]>
$

And when Ruby exits, the database will be removed from memory, leaving you with a clean slate again. You don’t need a Rails app directory or a SQLite database file; all you need is these two Ruby code files.

How it Works

If we’re just playing with Active Record models, we don’t need all of Rails, we just need a database adapter and Active Record itself. These two lines load the necessary libraries:

require ‘sqlite3’
require ‘active_record’

If you use the special value of “:memory:”, SQLite3 can write everything to a database in RAM, rather than a file on disk. Sure, everything disappears when Ruby exits, but that’s actually preferable when you’re just playing around. These lines set Active Record up to use an in-memory database:

ActiveRecord::Base.establish_connection(
adapter: ‘sqlite3’,
database: ‘:memory:’
)

Your model classes won’t work unless the database contains the appropriate tables and columns. A Rails app maintains its database setup in a file named db/schema.rb, and that file can be used to recreate a database from scratch, without running migrations. But the schema doesn’t have to be kept in a separate file; we can just throw it straight into our single-file app!

ActiveRecord::Schema.define do
create_table :owners, force: true do |t|
t.string :name
end
create_table :pets, force: true do |t|
t.string :name
t.references :owner
end
end

And then we need the actual model classes. These lines set them up:

class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
end
class Owner < ApplicationRecord
has_many :pets
end
class Pet < ApplicationRecord
belongs_to :owner
end

Now to load your makeshift Active Record environment, and set up the database. This line looks in the current directory for a file named vet.rb, and runs the code it contains:

require ‘./vet’

Once that’s done, you’re free to create new instances of your model classes, save them to the in-memory database, and load them back out again!

owner = Owner.create(name: “Jay”)
owner.pets.create(name: “Max”)
owner.pets.create(name: “Chai”)
p Owner.first.pets

Other Stuff to Try

You don’t even have to create multiple files for this – you can house all your code in a single file. For example, here’s a mini-app that lets you play with Post and Comment models from a blog.

The next time you’re troubleshooting an issue with your models, or you just want to show off your code, you don’t have to share a whole Rails app. Instead, you can create one of these miniature apps, and share everything you need with a single file!

P.S.: If you liked this post, you should try out our new Active Record Associations in Rails course!

The post Active Record Without a Rails App appeared first on Treehouse Blog.

From Web Development to iOS Developer: Laurie’s Story

Original Source: http://blog.teamtreehouse.com/web-developer-to-ios-developer

We first met Laurie Gray, an inspiring Scottish Treehouse student, two years ago when he shared his story with us. In less than a year of learning with Treehouse, Laurie had learned to code, switched career paths, started his own freelance business and landed a part-time job as an in-house web developer, which later became a permanent position. Since then, Laurie’s career has continued to evolve, and his journey as a programmer has taken a new direction. Today, Laurie has reached his dream career as a full-time iOS developer. Not only does his role satisfy his thirst for knowledge and intrigue for technology, but he also now works alongside a team of other talented developers.

We reconnected with Laurie to hear more about his experience evolving from web developer to iOS developer and to share his advice with other aspiring iOS developers.

Start learning to code today with a free trial on Treehouse.

What first encouraged you to learn to code and pursue a career in the tech industry?

From the moment I first saw the iOS App Store, heard about the iPhone and saw the power to put apps in people’s hands that they could physically interact with, I became increasingly interested in development. Programming suddenly became very relevant to me, however, at the time it was still shrouded in total mystery; it seemed to be like magic that code could make such amazing things. At the time I didn’t even know how to use a semi-colon correctly in English, never mind whilst programming, so I essentially had to learn everything from the very beginning.

I didn’t even know how to use a semi-colon correctly in English, never mind whilst programming, so I essentially had to learn everything from the very beginning.

I started to get into web development as a means of transitioning from my job at the time and did this outside of my working hours supporting my family as the sole-provider of income for our household. Initially, it was very difficult to pick up some of the most basic concepts, especially when learning Javascript, but over time it began to make more sense and my skills started to grow. I managed to get a part-time position as a frontend developer shortly afterward and then it became my full-time occupation. It was a marvelous feeling developing every day and I loved every second of that job, however, I began to develop apps for the company I was with and I was delighted to begin transitioning into my dream career of being an iOS app developer.

You’re now a full-time enterprise iOS developer. Tell us a little about how your career has evolved since you last shared your story with us.

When I last shared my story I was just starting out on my journey as a programmer. It was my dream to be one day working as an iOS developer, particularly on large-scale enterprise applications and I had no idea how much I would learn on the journey to making that dream become a reality. I have met many incredible and inspirational people along the way to help me reach where I am now (both inside and outside of the tech industry).

I was always the sole developer in my last position which was an interesting challenge. Now I am surrounded by phenomenal developers who constantly share their knowledge openly and don’t mind taking the time to help out when I’m really stuck.

One of the things which I’m so grateful for is that I have several mentors now. Having someone to direct you, give you helpful hints every now and then as well as show you ways of doing things that stretch your thinking has drastically changed the way I approach problems and coding in general. It has really pushed me forward these last few months and seeing their sheer fluency in several technologies has raised the bar for what I expect of myself and provided me with someone to model myself on.

web developer to ios developer

Having someone to direct you, give you helpful hints every now and then as well as show you ways of doing things that stretch your thinking has drastically changed the way I approach problems and coding in general.

What have you found the greatest challenge while learning to code?

The most challenging thing about learning to code is learning on your own for long periods of time. Traditional education gives you small outcomes with planned curriculums which may or may not be relevant to your end goal. Programming contrasts wildly with this! You tend to spend most of your time on the very edge of what you can understand and are trying to use that knowledge – while it is still very fresh – to solve some problem. Furthermore, a lot of this time is spent on your own, without anyone to show you if you’re doing it correctly or not. This can be very incredibly frustrating, especially when you don’t know why your code doesn’t work!

It can be easy to lose direction when you’re working towards being proficient in a certain language or framework and this can lead you into a place where you might get a bit lost on your journey.

What has the value of a Treehouse education meant to you?

Treehouse gave me something that I couldn’t find anywhere else: a track to follow with encouraging teachers. With the mountain of information out there I would have found it difficult to create anything concrete if I didn’t have some sort of route with a definite goal at the end. It was incredibly practical with less theory and more hands-on development and it met my thirst for knowledge where I could take several tracks in order to learn the skills I needed to be employable.

The teachers are super encouraging and somehow that really comes across in the videos. Positivity has an infinite impact on you and you need every bit of it you can get whilst learning to code.

Positivity has an infinite impact on you & you need it whilst learning to code.
Click To Tweet

What are your favorite aspects of working in the tech industry compared to your past career?

My thirst for knowledge has only ever been satisfied when working in tech. It is the only career I’ve had where every single day I am absolutely set to give my all from morning to night and I rise the next day loving it even more. I simply can’t get enough of it. The people within the community are so inspirational and creating things all day is just the best thing on earth. There is nothing quite like it!

What advice would you share with aspiring iOS developers?

I remember going to the stories page on Treehouse when I was starting out to read of people who had managed to transition into a job as an app developer. It really helped me get excited that it was possible and I want to tell those who are reading my humble story that in all honesty being an iOS developer is the most fulfilling job I have ever had. I absolutely love it. However, when you’re working towards making that dream a reality it is incredibly difficult. It feels like you’re going at it every day and not noticing any difference. I know how you feel!

I want to tell everyone who is interested in working in iOS that you absolutely can do it. No one can stop you. You’re limitless.

If I was to offer any piece of advice though I would say give yourself time, practice writing code and most importantly, build something you’re passionate about. Everyone gets into app development with a desire to make something of their own creation. Tap into that creativity and you’ll go much farther than just following other people’s lead.

Every now and then check your old work and you’ll see progress and always be working on something, no matter how small.

Most importantly I would say go out and actually meet real developers. Learning on your own makes it hard to know if you’re going at a good pace and talking things through with an iOS developer can really give you a lift and a catapult you forward towards your goal. Most developers will totally be able to relate to you even early on and will offer you advice and tips that can help. Also knowing people in the community opens doors for you later on.

My thirst for knowledge has only ever been satisfied when working in tech. It is the only career I’ve had where every single day I am absolutely set to give my all from morning to night and I rise the next day loving it even more. I simply can’t get enough of it.

Self-Taught Developer to Web Development Director: Jim’s Story

The post From Web Development to iOS Developer: Laurie’s Story appeared first on Treehouse Blog.

The CSS attr() function got nothin’ on custom properties

Original Source: https://css-tricks.com/css-attr-function-got-nothin-custom-properties/

Normally, the connection between CSS and HTML is that CSS selectors match HTML elements, and the CSS styles them. CSS doesn’t know about the actual content in the HTML. But there is a way CSS can get its hands on data in HTML, so long as that data is within an attribute on that HTML element.

It’s like this:

div::after {
content: attr(data-whatever);
}

That’s certainly interesting. You could use it for (rather inaccessible) tooltips, for example:

<button data-tooltip=”Information only mouse-having sighted people will see.”>
Button
</button>
button:hover::after {
content: attr(data-tooltip);
/* positioned and styled and whatnot */
/* ya, a :focus style would buy you a tad more a11y */
}

But you can’t put HTML in the attribute value, so those tooltips are limited to a string value, and couldn’t have a title, link, or anything like that inside them.

Here’s a better use case. There is an old print stylesheet chestnut where you use attr() to add the URL’s to links, so you can actually see what a link is linking to:

@media (print) {
a[href]::after {
content: ” (” attr(href) ” )”;
}
}

That’s clever. But what else? Could you pass a color down?

<h2 data-color=”#f06d06″>
Custom Colored Header
</h2>

That’s not invalid, but it isn’t useful.

h2 {
/* Not gonna work */
color: attr(data-color);
}

The value from attr() is a string. Even though that string is in the same format as a hex code, it won’t be used as a hex code.

Nor can you pass a URL that can actually be used in something like background-image(). Nor you can pass a unit like 3, 20px or 4rem or 0.8vw.

CSS’s attr() function is only strings, and strings are only really useful as content, and content (being unselectable and somewhat inaccessible) isn’t particularly useful anyway. You can’t select the text of psuedo content, for example, nor search for it, making it rather inacessible.

You know what can pass any sort of value and is equally easy to implement as attributes?

CSS custom properties!

You can pop them right into the style attribute of any element. Now those values are available to that element:

<button
style=”
–tooltip-string: ‘Ug. Tooltips.’;
–tooltip-color: #f06d06;
–tooltip-font-size: 11px;
–tooltip-top: -10px

>
Button
</button>

We’re passing a string to CSS above, but also a color and length values. Those values are immediately usable as-is:

button::after {
content: var(–tooltip-string);
color: var(–tooltip-color);
font-size: var(–tooltip-font-size);
}

Here’s that demo with some fiddly “logic” (would need to be improved a lot to be actdually useful) to allow variations:

See the Pen CSS Custom Properies Mo’ Betta’ than attr() by Chris Coyier (@chriscoyier) on CodePen.

This really isn’t any more accessible, for the record. If I were implementing tooltips for real, I’d probably read the heck out of this.

What about some other “good” use cases for attr()?

One that comes up a lot is responsive data tables. Imagine a table with headers along a top row and rows of data below:

<table>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
….
</tr>
</thead>
<tbody>
<tr>
<td>Chris</td>
<td>Coyier</td>

</tr>

</tbody>
</table>

Rows of data like that might become problematic on small screens (too wide). So in a reponsive data table, we might hide that top row, and show labels on a per-cell basis instead.

@media (max-width: 500px) {
thead {
display: none;
}
/* Need to reveal another label now that we’ve hidden the normal labels */
}

Where does that label come from? We could do…

. …
<tr>
<td data-label=”First Name”>Chris</td>
<td data-label=”Last Name”>Coyier</td>

</tr>

Then:

td::before {
content: attr(data-label);
/* Also display: block things and such */
}

That’s a pretty good use case. If we use some kinda of accessible hiding method for that <thead>, it might even pass a11y muster.

But this same exact thing is doable with CSS custom properties…

. …
<tr>
<td style=”–label: ‘First Name’;”>Chris</td>
<td style=”–label: ‘Last Name’;”>Chris</td>

</tr>
td::before {
content: var(–label);

}

Eric Bidelman pointed me to a method of using psueudo content to show an input’s value.

<style>
input {
vertical-align: middle;
margin: 2em;
font-size: 14px;
height: 20px;
}
input::after {
content: attr(data-value) ‘/’ attr(max);
position: relative;
left: 135px;
top: -20px;
}
</style>

<input type=”range” min=”0″ max=”100″ value=”25″>

<script>
var input = document.querySelector(‘input’);

input.dataset.value = input.value; // Set an initial value.

input.addEventListener(‘change’, function(e) {
this.dataset.value = this.value;
});
</script>

That feels a smidge dangerous to me since I didn’t think pseudo content was supposed to work on replaced elements like an <input>. It’s probably a job for output, and the JavaScript would be essentially the same. You could use pseudo content with the additional element, but there’s really no need for that.

Exploiting the fact that psuedo content can’t be copied is also clever. For example, GitHub does code block line numbering with data-line-number=”” and ::before { content: attr(data-line-number); }.

Nobody likes selecting line numbers when they are trying to copy code! Good use here (probably even more flexible than CSS counters), but again, something that CSS custom properties could handle as well.

<td style=”–line-num: 5″> … </td>

You could argue this is better because if you did want to use CSS counters, you could use that first value to kick things off and not need it on every line.

See the Pen Line Numbering by Chris Coyier (@chriscoyier) on CodePen.

Same deal with typographic trickery involving duplicating text in CSS for stylistic reasons. Check out this cool demo by Mandy Michael using attr(). I’m sure you can imagine how –heading: “Fracture”; could do the trick there.

The CSS3 Values spec (in Candidate Recommendation) has a way to make attr() useful

I’m not sure it matters much, as I’d argue CSS custom properties are a near total replacement for attr(), but the spec does specifically cover this, presumably as an attempt to make it more useful.

The idea is to set the type of value as you grab it in CSS.

<div data-color=”red”>Some Words</div>
div {
color: attr(data-color color);
}

Or…

<span data-size=”50″>span</span>
span {
font-size: attr(data-size px);
}

But as far as I can tell, no browser supports this.

The CSS attr() function got nothin’ on custom properties is a post from CSS-Tricks

New Illustrated Lettering Class with Gemma O’Brien

Original Source: http://justcreative.com/2017/10/26/illustrated-lettering-class-gemma-obrien/

Fellow Aussie, Gemma O’Brien (aka MrsEaves), is a talented award-winning artist who I started following a few years back when I saw her speak at a design conference. She creates incredible, envy producing lettering, illustration and typographic work.

The good news is that she has just released a brand new Skillshare lettering class.

In the class, you’ll create an intricate, illustrated letterform — and level up your skills with new creative approaches to typography, drawing, digital layout, and more.

Every lesson breaks down her step-by-step approach, while also sharing illustration and composition techniques you can add to your personal repertoire and bring to projects of your own.

All are invited to join this class and flex their creativity. Whether you’re new to illustration and looking for a weekend project, or a seasoned artist aiming to create a complex piece, you’ll gain insights and skills for use again and again.

Once you dive in to Gemma’s creative lettering, you’ll never look at illustration the same way again.

2 Free Months of Skillshare Premium!

Get unlimited access to this premium class and 17,000+ more with Skillshare Premium. .

» Get started for free