Skip to content

Instantly share code, notes, and snippets.

View g0t4's full-sized avatar
🏁

Wes Higbee g0t4

🏁
View GitHub Profile
@g0t4
g0t4 / tap.kt
Created October 15, 2014 23:39
A ruby like tap method for kotlin, except for any type
/**
* Provide a means to fluently tap into a chain of method calls so as not to need to declare unnecessary variables
* */
public fun <T : Any, R> T.tap(tap: (T) -> R): T {
tap(this)
return this
}
// here's an example where I'm in a fluent builder and I'd like to log the URI of the request without introducing a variable
val response = this.builds.queryParam("locator", "buildType:{buildTypeId},count:1,personal:false,canceled:false")
@g0t4
g0t4 / gist:30a5d7f5a07146d6bad3
Created October 15, 2014 22:21
Null safety, proving something is null in kotlin and then not needing to deal with it thereafter
// In Kotlin, I can force the source of a reference to ensure it's not null, that way every thing thereafter doesn't have to deal with null references
// This is what I refer to as fixing things up stream, of course when appropriate.
// Typically sources of references don't both to check for null and even if they do, they can't make explicit that they've taken care of that check. So every consumer of that reference theoretically may need to check.
// In this example, there's no reason the userId, password and serverUrl should ever be null. Unfortunately because of interop with java, that's not a contractual guarantee.
// So at the point that I produce these values for my own use, I perfom the check in one place, stop everything if my assumption is not valid, and otherwise be on my merry way never to worry about null references after this point
abstract class Restore(val runner: BuildRunnerContext) {
val logger: SimpleBuildLogger = runner.getBuild().getBuildLogger()
val client: TeamCityClient
{
@g0t4
g0t4 / hackNancyRazorPageBaseType
Last active August 29, 2015 13:55
Hack to set a custom base view with Nancy and Razor
// At this time Nancy's Razor view engine doesn't let you set a default base class like ASP.NET web pages does with pageBaseType, if you want to hack one in here is how:
// First create your custom type, this one writes out hack for everything, so obviously remove that unless you want that :)
public abstract class MyRazorPage<T> : NancyRazorViewBase<T>
{
public override void Write(object value)
{
base.WriteLiteral("hack");
}
@g0t4
g0t4 / gist:8718256
Last active August 29, 2015 13:55
Razor allow custom html builders to use @ syntax and not encode the output
// Out of the box, WebViewPage essentially does this to write content:
Output.Write(HttpUtility.HtmlEncode(content));
// And HttpUtility.HtmlEncode will encode anything not marked with the IHtmlString interface
// If we have a custom html builder we have to use something like this:
@Html.Raw(safeBuilder)
// This is a lot of extra typing
[Test]
[Timeout(2000)]
public async Task WriteToFile_StreamsChanged()
{
using (var watcher = new ObservableFileSystemWatcher(c => { c.Path = TempPath; }))
{
var firstChanged = watcher.Changed.FirstAsync().ToTask();
watcher.Start();
File.WriteAllText(Path.Combine(TempPath, "Changed.Txt"), "foo");
@g0t4
g0t4 / ko.typeahead.binder.js
Created April 15, 2013 03:47
knockoutjs binder for bootstrap typeahead
// FYI YMMV this was just a first pass and I know it has some issues at times that I need to workout
// usage
// source: a function that takes the query (text entered by user) and a callback (process), if source is synchronous it should return the results and ignore the callback, otherwise it should return nothing and use the callback to return the results
// selectedId: the model property to bind the id to
// value: the model property to bind the text value of the selection to
// data-bind="typeahead: { source: App.view.targets.typeAheadSource, selectedId: target._id }, value: target.name"
// note I also use this little helper class to wrap up all this functionality
// it takes a url to query the results for asynchrnous data sets and has an init method to call to query the data initially.
@g0t4
g0t4 / ko.elastic.binder.js
Created April 15, 2013 03:43
knockoutjs binder for jquery elastic plugin
require(['knockout', 'jquery.elastic'], function (ko) {
ko.bindingHandlers.elastic = {
// todo probably should make this destroy when the element is destroyed.
update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
$(element).elastic();
}
}
});
@g0t4
g0t4 / gist:4271829
Created December 12, 2012 21:34
Why manually replace crap over and over, why not write code to do it if it saves time :)
[Test]
public void METHOD_SCENARIO_EXPECTATION()
{
var path = @"..\..\..\View.spark";
var code = File.ReadAllLines(path);
for (int lineNumber = 0; lineNumber < code.Length; lineNumber++)
{
var line = code[lineNumber];
var classControlLabel = "class=\"control-label\"";
if(line.Contains(classControlLabel))
@g0t4
g0t4 / gist:4271057
Created December 12, 2012 20:01
Mongodb editing file information with c# driver
//Easier to just pull the file collection and edit the files documents, just be careful, example:
public void SaveMetadata(string id, MetadataJson metadata)
{
var gridFs = FilesContext.GetGridFs();
var files = gridFs.Database.GetCollection(gridFs.Settings.FilesCollectionName);
var file = files.FindOneById(new BsonObjectId(id));
var metadataDocument = file["metadata"].AsBsonDocument;
metadataDocument.Set("comment", metadata.comment ?? string.Empty);
@g0t4
g0t4 / gist:4261025
Created December 11, 2012 18:56
KISS & AJAX Deletes
// I run across this type of code often (note ASP.Net MVC)
[HttpPost]
public string Delete(ObjectId id)
{
var record = _Database.Get<Record>(id);
if (record == null)
{
return "No matching record!";
}