I'm trying to follow along the excellent tutorial backbonerails produced by Brian Mann. Unfortunately (for me because I'm a noob) he's using coffeescript. What's confusing is my assumptions of the following code:
class App.Views.Users extends Backbone.View
I believed was the equivalent of:
Users = Backbone.View.extend({});
in plain javascript. However, when I place the coffeescript code in trycoffeescript I get:
var _ref,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
App.Views.Users = (function(_super) {
__extends(Users, _super);
function Users() {
_ref = Users.__super__.constructor.apply(this, arguments);
return _ref;
}
return Users;
})(Backbone.View);
My question is am I wrong in my assumption of what plain javascript should produce, am I incorrectly approaching the way to interpret the coffee script, or am I beyond hope?
Classes in coffeescript can't guarantee that the classes they're extending have an extend method, so it wouldn't be possible for the coffeescript to compile to Backbone.View.extend, without specifically requiring all the classes it's used with to provide the extend method.
However, if you look at the source of _.extend (which Backbone uses) you'll see that it's fairly similar to the __extends method that coffeescript generates and uses.
The coffeescript compiled version is obviously more verbose, but in practice I've never noticed a difference between class MyView extends Backbone.View and MyView = Backbone.View.extends({}}; so you can probably use whichever one you prefer.
EDIT: One possible difference is actually the super coffeescript keyword, which will only work if you're using coffeescript classes. However, you should still be able to replicate that functionality with .extends by calling the superclass function directly.
Related
Please explain the functional difference between Customize and Register, when to use one over the other. The TestCustomize example below fails and the TestRegister passes. I expected the customize script to work fine. It reads to me in English as:
"When generating an HttpClient, use a post-processing lambda on it before providing the specimen".
But what I get is an HTTP address with a GUID in it, clearly generated by AutoFixture.
[Fact]
public void TestCustomize()
{
var fixture = new Fixture();
fixture.Customize<HttpClient>(c =>
{
//c.OmitAutoProperties(); makes no difference
c.Do(x => x.BaseAddress = new Uri("http://myval"));
return c;
});
var client = fixture.Create<HttpClient>();
Assert.Equal("http://myval/", client.BaseAddress.ToString());
}
[Fact]
public void TestRegister()
{
var fixture = new Fixture();
fixture.Register(() => new HttpClient
{
BaseAddress = new Uri("http://myval")
});
var client = fixture.Create<HttpClient>();
Assert.Equal("http://myval/", client.BaseAddress.ToString());
}
This has nothing to do with Customize vs. Register. In fact, if you look at the source code for Register, you'll see that it's only a convenience method over Customize.
The problem lies in the use of Do. If you look at the signature of Do, you'll see that it has this type:
IPostprocessComposer<T> Do(Action<T> action)
Notice that the method returns a value. In Functional style, or, if you will, following Command-Query Separation, the method doesn't mutate the instance on which it's defined, but rather returns a new object with the changed behaviour.
When one writes:
c.Do(x => x.BaseAddress = new Uri("http://myval"));
one immediately discards the return value with the changed behaviour. In languages like F# or Haskell, you'd get a compile-time notification if you wrote code like that, telling you that you'd be ignoring the return value of a function call, but C# doesn't do that.
In any case, AutoFixture's APIs are designed as fluent interfaces. The intent is that you chain method calls together:
fixture.Customize<HttpClient>(c => c
.Without(x => x.BaseAddress)
.Do(x => x.BaseAddress = new Uri("http://myval")));
You still need Without (or, if you will, OmitAutoProperties) to turn off the default auto-property behaviour, because otherwise, BaseAddress will be overwritten by the auto-property feature.
This version of the test passes:
[Fact]
public void TestCustomize()
{
var fixture = new Fixture();
fixture.Customize<HttpClient>(c => c
.Without(x => x.BaseAddress)
.Do(x => x.BaseAddress = new Uri("http://myval")));
var client = fixture.Create<HttpClient>();
Assert.Equal("http://myval/", client.BaseAddress.ToString());
}
I'm using ScalaJs angular and Upickle and I try to create a filter to transform an unknown class to JSON.
What I tried :
my scope :
var myScope: MyClass = js.native
my filter:
#injectable("copy")
class CopyFilter extends Filter[Any] {
override def filter(any: Any): js.Dynamic = {
val myClass = any.getClass
fromClassToJsValue[myClass](any)
}
}
my function
def fromClassToJsValue[A](value: A)(implicit serializer: Writer[A]): js.Dynamic =
JSON.parse(write(value))
In this case my problem is getClass which returns Class[_] and not MyClass
Is there any solution to find MyClass? (Or maybe any other solution to derive a type Any?)
Broadly speaking, uPickle isn't designed to deal with that; I don't think any of the other JSON serializers are, either. That sort of Any-friendly serialization is usually based on reflection, which mostly isn't available in the JavaScript environment.
I suspect you do need a Filter per case class, albeit probably a one-liner. (Possibly done as a base trait that you mix into the case classes themselves, but I don't know Angular, so I know don't what the constraints look like.)
I want to have the following functionality in AngularJs as I have in C++ or Java(while I used GWT).
I have Class A with list of references to Class B's object and vica-versa so that I can say something like this. A's_object->B's_reference->show_B's_property
class A{
list<B*> B_ref;//points to B's class objects
......and more
}
class B{
list<A*> A_ref;//points to A's class objects
......and more
}
I mean is it even possible?Please Guide
AngularJs is a framework that uses html, css, and Javascript to easily create single-page applications. Your question would pertain to Javascript rather than the AngularJs framework.
The kind of behavior that you are looking for would be difficult to see in Javascript due to the nature of the language. Javascript is not a language that supports classes in the same way as C++ and Java. Javascript is a dynamic language that is functional based, rather than object oriented.
Javascript can support classes, but not in the same manner as you would be used to in languages like C++ and Java. Javascript instead uses prototypes. Basically, each object has an associated prototype (which is somewhat similar to the static behavior in C++ and Java classes) and this prototype can be decorated with methods and properties. New objects are cloned from existing objects, and the prototypes of the new objects inherits from the original prototype.
This allows many object-oriented features to be imitated in Javascript. I would recommend that you read up about the difference between Javascript and languages like C++.
http://en.wikipedia.org/wiki/Prototype-based_programming
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript
function A(color) {
this.bRef = [];
this.color = color;
// and more
}
function B(name) {
this.aRef = [];
this.name = name;
// and more
}
var a = new A();
var b1 = new B('foo');
var b2 = new B('bar');
a.bRef.push(b1);
a.bRef.push(b2);
var a1 = new A('red');
var a2 = new A('black');
b1.aRef.push(a1);
b1.aRef.push(a2);
console.log(a.bRef[1].name); // bar
console.log(a.bRef[0].aRef[0].color); // red
console.log(a.bRef[0].aRef[1].color); //black
b2.name = 'boo';
console.log(a.bRef[1].name); // boo
I'd like to check if the object x implements (is instance of) the mixin MyInterface:
Ext.define('MyInterface', {
interfaceMethod: Ext.emptyFn
});
Ext.define('Foo', {
mixins: {
myInterface: 'MyInterface'
}
});
var x = new Foo();
doesn't work work:
console.log(x instanceof MyInterface);
ugly workaround:
var isInstanceOfMyInterface = false;
for (var i in x.mixins) {
if (x.mixins[i].$className == 'MyInterface') {
isInstanceOfMyInterface = true;
}
}
console.log(isInstanceOfMyInterface);
The workaround has one major issue: it doesn't work if a subclass of MyInterface is used.
jsfiddle
A pattern the Ext core uses is to apply a mixin specific property so you can test for its existence. It's a lot cheaper than an instanceof check as well. For example:
Ext.define('MyInterface', {
isMyInterface: true,
interfaceMethod: Ext.emptyFn,
});
Ext.define('Foo', {
mixins: {
myInterface: 'MyInterface'
}
});
var x = new Foo();
console.log(x.isMyInterface);
Mixins solve the problem of multiple inheritance because there is no way to make class C inherit from both A and B in plain JavaScript. The logic is then let class C to inherit from A and use class B as mixin. The mixin B is a sort of repository of additional methods and properties for C.
When the mixin B is used in class C, all its methods and properties are copied to the prototype of C and when C is instantiated it contains its own methods, methods of A, because it inherits from A, and B because mixin's methods are added to it.
Also, C can use more than one mixin to add additional methods/properties. Using mixin does not change the class name of the target class, C stays C.
Internally in Ext used mixins are held as object in mixins object of the target class as name/value pairs.
Summed together, your way is already the fine way to check if a class uses a mixin, nevetheless, it can be improved:
you can implement the above code as a method of the class(es) you want to check
you can break the above look once the mixin is found to save some cycles
Currently, I'm using custom made fake objects that behind the scenes use NSubstitute which creates the actual objects but it's becoming very hard to maintain as the project grows, so I'm trying to find alternatives and I'm hoping that AutoFixture is the right tool for the job.
I read the documentation and I'm struggling because there's very little to no documentation and I read most of the blog posts by Mark Seemann including the CheatSheet.
One of the things that I'm having hard time to grasp is how to create an object with a constructor that have parameters, in my case I need to pass argument to CsEmbeddedRazorViewEngine as well as HttpRequestBase to ControllerContext.
The way I see it is that I need to create a fake objects and finally create a customization object that injects them to
I also looked into NBuilder it seems slightly more trivial to pass arguments there but I've heard good things about AutoFixture and I would like to give it a try. :)
I'm trying to reduce the amount of fake objects I have so here is a real test, how can I do the same thing with AutoFixture?
[Theory,
InlineData("en-US"),
InlineData("en-us"),
InlineData("en")]
public void Should_return_the_default_path_of_the_view_for_enUS(string language)
{
// Arrange
const string EXPECTED_VIEW_PATH = "~/MyAssemblyName/Views/Home/Index.cshtml";
CsEmbeddedRazorViewEngine engine = CsEmbeddedRazorViewEngineFactory.Create(ASSEMBLY_NAME, VIEW_PATH, string.Empty);
string[] userLanguage = { language };
HttpRequestBase request = FakeHttpRequestFactory.Create(userLanguage);
ControllerContext controllerContext = FakeControllerContextFactory.Create(request);
// Act
ViewEngineResult result = engine.FindPartialView(controllerContext, VIEW_NAME, false);
// Assert
RazorView razorView = (RazorView)result.View;
string actualViewPath = razorView.ViewPath;
actualViewPath.Should().Be(EXPECTED_VIEW_PATH);
}
P.S. I'm using xUnit as my testing framework and NSubstitute as my mocking framework should I install both AutoFixture.Xunit and AutoFixture.AutoNSubstitute?
UPDATE: After learning more and more about it I guess it is not the right tool for the job because I tried to replace my test doubles factories with AutoFixture rather than setting up my SUT with it.
Due to odd reason I thought it's doing the same thing NBuilder is doing and from what I can see they are very different tools.
So after some thinking I think I'll go and change the methods I have on my test doubles factories to objects then use AutoFixture to create my SUT and inject my test doubles to it.
Note: I don't have the source code for the CsEmbeddedRazorViewEngine type and all the other custom types.
Here is how it could be written with AutoFixture:
[Theory]
[InlineAutoWebData("en-US", "about", "~/MyAssemblyName/Views/Home/Index.cshtml")]
[InlineAutoWebData("en-US", "other", "~/MyAssemblyName/Views/Home/Index.cshtml")]
public void Should_return_the_default_path_of_the_view_for_enUS(
string language,
string viewName,
string expected,
ControllerContext controllerContext,
CsEmbeddedRazorViewEngine sut)
{
var result = sut.FindPartialView(controllerContext, viewName, false);
var actual = ((RazorView)result.View).ViewPath;
actual.Should().Be(expected);
}
How it works:
It uses AutoFixture itself together with it's glue libraries for xUnit.net and NSubstitute:
PM> Install-Package AutoFixture.Xunit
PM> Install-Package AutoFixture.AutoNSubstitute
With InlineAutoWebData you actually combine inline values and auto-generated data values by AutoFixture – also including Auto-Mocking with NSubstitute.
internal class InlineAutoWebDataAttribute : CompositeDataAttribute
{
internal InlineAutoWebDataAttribute(params object[] values)
: base(
new InlineDataAttribute(values),
new CompositeDataAttribute(
new AutoDataAttribute(
new Fixture().Customize(
new WebModelCustomization()))))
{
}
}
Remarks:
You could actually replace the WebModelCustomization customization above with AutoNSubstituteCustomization and it could work.
However, assuming that you are using ASP.NET MVC 4, you need to customize the Fixture instance with:
internal class WebModelCustomization : CompositeCustomization
{
internal WebModelCustomization()
: base(
new MvcCustomization(),
new AutoNSubstituteCustomization())
{
}
private class MvcCustomization : ICustomization
{
public void Customize(IFixture fixture)
{
fixture.Customize<ControllerContext>(c => c
.Without(x => x.DisplayMode));
// Customize the CsEmbeddedRazorViewEngine type here.
}
}
}
Further reading:
Encapsulating AutoFixture Customizations
AutoData Theories with AutoFixture
I ended up doing this.
[Theory,
InlineData("en-US", "Index", "~/MyAssemblyName/Views/Home/Index.cshtml"),
InlineData("en-us", "Index", "~/MyAssemblyName/Views/Home/Index.cshtml"),
InlineData("en", "Index", "~/MyAssemblyName/Views/Home/Index.cshtml")]
public void Should_return_the_default_path_of_the_view(string language, string viewName, string expected)
{
// Arrange
CsEmbeddedRazorViewEngine engine = new CsEmbeddedRazorViewEngineFixture();
ControllerContext controllerContext = FakeControllerContextBuilder.WithLanguage(language).Build();
// Act
ViewEngineResult result = engine.FindPartialView(controllerContext, viewName, false);
// Assert
string actualViewPath = ((RazorView)result.View).ViewPath;
actualViewPath.Should().Be(expected);
}
I encapsulated the details to setup my SUT into a fixture and used the builder pattern to handle my fakes, I think that it's readable and pretty straightforward now.
While AutoFixture looks pretty cool, the learning curve seems long and I will need to invest enough time to understand it, for now, I want to clean-up my unit tests and make them more readable. :)